2

I have a flat json array that store data like this:


[
 {
  "prop1": "prop1Data1"
 },
 {
  "prop2": "prop2Data1"
 },
 {
  "prop3.name": "Tom"
 }
]

How can I convert this data into simple json object in node js like this:


{ "prop1": "prop1Data1", "prop2": "prop2Data1", "prop3.name": "Tom" }
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
realcodes
  • 259
  • 1
  • 5
  • 17

2 Answers2

7

You could use Object.assign and use spread syntax ... for the array.

var array = [{ prop1: "prop1Data1" }, { prop2: "prop2Data1" }, { "prop3.name": "Tom" }],
    object = Object.assign({}, ...array);

console.log(object);

ES5 with Array#reduce and by iterating the keys.

var array = [{ prop1: "prop1Data1" }, { prop2: "prop2Data1" }, { "prop3.name": "Tom" }],
    object = array.reduce(function (r, o) {
        Object.keys(o).forEach(function (k) {
            r[k] = o[k];
        });
        return r;
    }, {});

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The way that I've done it was like so, since it is within an array.

var original = [{"prop1": "prop1Data1"},{"prop2": "prop2Data1"},{"prop3.name": "Tom"}];

var propStore = {
   prop1 : '',
   prop2 : '',
   prop3 : ''
}
propStore.prop1 = original[0]["prop1"];
propStore.prop2 = original[0]["prop2"];
propStore.prop3 = original[0]["prop3"];

console.log(propStore);
ElementCR
  • 178
  • 12