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}] 
2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

It works, thank you! I didn't thinked about reduce
0

try this code

let extractedKeys = Object();

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

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

console.log(extractedKeys);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.