0

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}] 
  • 1
    Smart-quotes in code make it harder for people to work with your code. – Dave Newton Apr 07 '21 at 16:00
  • Does this answer your question? [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Heretic Monkey Apr 07 '21 at 17:03

3 Answers3

1

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

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);
blex
  • 24,941
  • 5
  • 39
  • 72
0

try this code

let extractedKeys = Object();

for(i = 0; i < objectArray.length ; i++){

     extractedKeys[objectArray[i]['name']] = 0;
}

console.log(extractedKeys);
Me Bottle O Scrumpy
  • 266
  • 1
  • 3
  • 12