简体   繁体   English

将动态生成的对象数组合并为单个 object

[英]Merge array of dynamically generated objects into single object

I'm struggling to convert the below JSON into expected JSON format using JavaScript.我正在努力使用 JavaScript 将以下 JSON 转换为预期的 JSON 格式。

Current JSON:当前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:预计 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.注意:上面代码中的家具只有 static。除此之外,所有键和值都是动态生成的。

You could look for arrays and create a joined object, otherwise flat the deeper level.你可以寻找 arrays 并创建一个连接的 object,否则更深层次。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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