0

I know this has been asked before, but every solution I found isn't doing it the way I need it.

The Array

[ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ]

Object I Need

{
"Title": "Default Text", 
"Title2": "Default Text2"
}

Everything I try seems to return this which is wrong:

{ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} }

I've tried most things I found here on SO.. the last one I've tried that is formatting it wrong is:

let obj = Object.assign({}, arrayHere);

What I want:

WHat I need

What I keep getting, but is wrong:

What I keep getting, but is wrong

0

4 Answers 4

2

Use Array.prototype.reduce() function:

var arr = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ],
    result = arr.reduce((r,o) => {r[o.key] = o.value; return r; }, {});

console.log(result);

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

3 Comments

ok let me try brb
IT WORKED THANK YOU
@user1189352, you're welcome
1

You could assign the single created objects with Array#map and Object.assign

var array = [{ key: "Title", value: "Default Text" }, { key: "Title2", value: "Default Text2" }];
    object = Object.assign({}, ...array.map(o => ({ [o.key]: o.value })));
    
console.log(object);

Comments

0
const a = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];

function convertArr(arr) {
    const res = {};

    a.forEach((item) => 
       res[item.key] = item.value;
    })
    return res;
}

convertArr(a);

Comments

0

Using Array.prototype.map(),

var Object = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];

var result = Object.map(function(obj) {
             var rObj = {};
             rObj[obj.key] = obj.value;
             return rObj; });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.