简体   繁体   中英

How to turn an array into an object in Javascript

I have an array like

let arr = [
  { key: "Text1", value: "Line 1" },
  { key: "Text2", value: "Line 2" },
  { key: "Text3", value: "Line 3" }
]

and I want to turn it into

let obj = {
  "Text1": "Line1",
  "Text2": "Line2",
  "Text3": "Line3"
}

in es6 i was trying something like this but that's definitely wrong. Any help please?

let temp = Object.assign({}, ...arr.map( {key, value} => ( {key, value} ) ));

You could solve this with reduce:

arr.reduce((o, el) => { 
    o[el.key] = el.value; 
    return o; 
}, {});

returns

{Text1: "Line 1", Text2: "Line 2", Text3: "Line 3"}

You could use Object.assign and a destructuring and a spread syntex for the items of the mapped objects.

Basically you need more parenthesis around the arguments and a computed key.

Object.assign({}, ...arr.map(({ key, value }) => ({ [key]: value })));
//                           ^              ^                          parenthesis
//                                                  ^   ^              computed property

 let arr = [{ key: "Text1", value: "Line 1" }, { key: "Text2", value: "Line 2" }, { key: "Text3", value: "Line 3" }], result = Object.assign({}, ...arr.map(({ key, value }) => ({ [key]: value }))); console.log(result); 

You can do it like this

let arr = [
      { key: "Text1", value: "Line 1" },
      { key: "Text2", value: "Line 2" },
      { key: "Text3", value: "Line 3" }
    ]

    var obj ={};
    arr.forEach(function(value){
    obj[value.key]=value.value;
    })

console.log(obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM