Home > database >  Merge array of dynamically generated objects into single object
Merge array of dynamically generated objects into single object

Time:02-10

I'm struggling to convert the below JSON into expected JSON format using JavaScript.

Current JSON :

    {
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}

expected JSON:

{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}

Note: furniture in above code is only static. Apart from that all keys and values are dynamically generated.

CodePudding user response:

You could look for arrays and create a joined object, otherwise flat the deeper level.

const
    flat = object => Object.fromEntries(Object
        .entries(object)
        .map(([k, v]) => [k, Array.isArray(v)
            ? Object.assign({}, ...v)
            : v && typeof v === 'object' ? flat(v) : v
        ])),
    data = { furniture: { matter: [{ matter1: "Matter 1 value" }, { matter2: "Matter 2 value" }, { matter3: "Matter 3 value" }], suspense: [{ suspense1: "suspense 1 value" }, { suspense2: "suspense 2 value" }], Direct: [{ System: "System value" }], Road: [{ "Road key 1 ": "Road value " }] }, Diversity: { "Sistema de direção": "Hidráulica" } },
    result = flat(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

try this

var furniture = {};
for (const property in jsonOrig.furniture) {
  var newObj = {};
  jsonOrig.furniture[property].forEach((value) => {
    for (const prop in value) {
      newObj[prop] = value[prop];
    }
    furniture[property] = newObj;
  });
}

var newJson = { furniture: furniture };
  • Related