简体   繁体   中英

Merge array of dynamically generated objects into single object

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM