2

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

4 Answers 4

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

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

6 Comments

When I try to use the syntax result = Object.assign({}, ...arr.map I get a syntax error at ...arr.map
@Jodo1992, which browser are you using? does your browser suppports ES6?
Not using a browser. This is involved with a mobile app. Just trying to accomplish the same exact thing the OP was trying to do in JS
maybe it is not ES6 compliant, but i am wondering why Object.assign is working.
The problem I don't think is Object.assign, it is the syntax ...arr.map. It doesn't not know what to do with the punctuation
|
3

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"}

Comments

2

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)

Comments

0

You can do this with .reduce

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

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.