Reputation: 11
I have the following array with objects
objectArray = [{name: “E-mail”, data_type: “text”}, {name: “Number”, data_type: “text”}, {name: “Person”, data_type: “text”}]
I need to extract just the name
prop from the array object as a key in a new object like this:
counterObject = {E-mail: 0, Number: 0, Person: 0}
I've tried to map
the array like this
objectArray((elem) => {
return {[elem.name]:0};
}))
and I've got the following result:
[{Text: 0}, {Number: 0}, {E-mail: 0}, {Person: 0}, {Upload: 0}, {Date: 0}, {Link: 0}]
Upvotes: 0
Views: 59
Reputation: 160231
const arr = [{ name: "E-mail" }, { name: "Number" }, { name: "Person" }];
const result = {};
arr.forEach(obj => result[obj.name] = 0);
console.log(result);
reduce
is another solution, but IMO it's less readable, and has the disadvantage of continually creating/shallow-copying the accumulator.
Upvotes: 1
Reputation: 282
try this code
let extractedKeys = Object();
for(i = 0; i < objectArray.length ; i++){
extractedKeys[objectArray[i]['name']] = 0;
}
console.log(extractedKeys);
Upvotes: 0