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" }
4
  • There was almost exact question few minutes ago. stackoverflow.com/questions/43008212/… Commented Mar 24, 2017 at 20:21
  • Hmm, not exactly. array[0]? Please also read the usage description of json. Commented Mar 24, 2017 at 20:24
  • @maytham-ɯɐɥʇʎɐɯ, not really. there are strings and not objects. Commented Mar 24, 2017 at 20:29
  • Ok I got your point Commented Mar 24, 2017 at 20:31

2 Answers 2

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

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

Comments

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

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.