2

Guys. I have array like this

array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

And I want to edit this array to

array = [ "A":{name:"A",data:"..."},"B":{name:"B",data:"..."},"C":{name:"C",data:"..."}

How could I set object key from its own value?

5
  • array = array.map(elem => ({ [elem.name]: elem })); Commented Jan 14, 2020 at 15:34
  • 1
    You can't, because [ "A":{name:"A",data:"..."} ] is not a valid array (arrays don't have named keys). You have to construct a new object { "A":{name:"A",data:"..."} } Commented Jan 14, 2020 at 15:35
  • are you sure, you want an array with properties? Commented Jan 14, 2020 at 15:35
  • shouldn't you create object instead of array? Commented Jan 14, 2020 at 15:37
  • Oh, You guys are right. then, I'll create it as object. So much thanks for your advise. Commented Jan 14, 2020 at 15:40

4 Answers 4

2

For getting an object, you could take Object.fromEntries with the mapped key/value pairs

var array = [{ name: "A", data: "..." }, { name: "B", data: "..." }, { name: "C", data: "..." }],
    result = Object.fromEntries(array.map(o => [o.name, o ]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

Alternatively you can perform a reduction on the array which for each element adds a key/value pair to the accumulator object : array.reduce((acc, curr) => { acc[curr.name]=curr; return acc; }, {})
2

Try this:

console.log(array.map(el => ({[el.name]: el})));

Comments

1

JavaScript array doesn't work that way. An array's index value can only have an increasing numeric indexes([0, 1, ..., n]). If you wan't to create such list you can create the object instead of an array.

const array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}];
const newList = {};

array.forEach(obj => {
    newList[obj.name] = obj;
});

console.log({ newList });

In this way you can create the object out of array. You can then loop the object's keys like in arrray using:

Object.keys(newList).forEach((key) => {
  console.log(newList[key]);
})

. Hope it helps.

Comments

0

Just do this.

var arr = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

var output = arr.map(elem => ({[elem.name]: elem}))

console.log(output)

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.