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

user1189352
  • 3,628
  • 12
  • 50
  • 90

4 Answers4

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);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
Pruthvi P
  • 536
  • 1
  • 7
  • 31
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; });
Stanley
  • 9
  • 1