Stanciu Patrick
Stanciu Patrick

Reputation: 11

Extract javascript array value as Object key

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

Answers (3)

Dave Newton
Dave Newton

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

Me Bottle O Scrumpy
Me Bottle O Scrumpy

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

blex
blex

Reputation: 25634

You can use reduce for this:

const objectArray = [{name: "E-mail", data_type: "text"}, {name: "Number", data_type: "text"}, {name: "Person", data_type: "text"}];

const result = objectArray.reduce((res, o) => ({ ...res, [o.name]: 0 }), {});

console.log(result);

Upvotes: 0

Related Questions