I have an array of objects. I want to efficiently extract keys and its value out of it.
Example:
let data = [{'Car':'Honda'}, {'car':'Volvo'}];
I want car as key and its values separately. How I can achieve it in efficient manner (even using lodash)?
Expected output will be:
key : Car value : Honda
key : car value : Volvo
I have an array of objects. I want to efficiently extract keys and its value out of it.
Example:
let data = [{'Car':'Honda'}, {'car':'Volvo'}];
I want car as key and its values separately. How I can achieve it in efficient manner (even using lodash)?
Expected output will be:
key : Car value : Honda
key : car value : Volvo
Share
Improve this question
edited Oct 18, 2021 at 20:32
pride
852 silver badges11 bronze badges
asked Jul 12, 2018 at 19:59
Deepender SharmaDeepender Sharma
4901 gold badge6 silver badges26 bronze badges
3
- 5 What is expected output? keys and values in which format? in array, in bined object? – Zohaib Ijaz Commented Jul 12, 2018 at 20:01
- 2 What is your expected output? What have you tried so far? We can't help you if you don't show your work. – Soviut Commented Jul 12, 2018 at 20:01
-
do you mean something like this?
data.map(Object.entries);
– Thomas Commented Jul 12, 2018 at 20:13
4 Answers
Reset to default 4You can iterate over the array and access the key and the value of properties for each object in question.
let data = [{
'Car': 'Honda',
'hello': 'hi'
}, {
'car': 'Volvo'
}];
data.forEach((obj) => {
Object.keys(obj).forEach((key) => {
console.log("key : " + key + " - value : " + obj[key]);
});
});
lodash snippet
let data = [{
'Car': 'Honda',
'hello': 'hi'
}, {
'car': 'Volvo'
}];
_.forEach(data, (obj) => {
_.forEach(Object.keys(obj), (key) => {
console.log("key : " + key + " - value : " + obj[key]);
});
});
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.core.min.js"></script>
Object.entries
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
const newArray = data.map((item) => Object.entries(item));
// [[['Car', 'Honda']], [['car', 'Volvo']]]
You can use Object.entries(obj)
to iterate over the keys and values.
data.forEach((obj) =>
Object.entries(obj).forEach(([key, value]) =>
console.log(key, value)));
let data = [{
'Car': 'Honda',
'hello': 'hi'
}, {
'car': 'Volvo'
}];
data.forEach((obj) =>
Object.entries(obj).forEach(([key, value]) =>
console.log(key, value)));
Plain and simple way to do it would be:
var data = [{
'Car': 'Honda'
}, {
'Car': 'Volvo'
}];
var j = 0;
var carNames= [];
for (var i = 0; i < data.length; i++){
var nameOfCar = data[i];
if(nameOfCar.hasOwnProperty('Car')){
carNames[j] = nameOfCar['Car'];
j++;
}
}
console.log(carNames);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742358443a4428907.html
评论列表(0条)