简体   繁体   English

将 json 个对象的值组合成一个具有唯一 object 个键及其值的数组

[英]Combining values of json objects into an array with unique object keys and its values

I have an array of JSON objects that might or might not have common object key such as我有一个 JSON 对象数组,这些对象可能有也可能没有公共 object 键,例如

const array = [ 
    {
      star: { apples: [ [Object], [Object] ] },
      circle: { apples: [ [Object] ] }
    },
    {
      star: { oranges: [ [Object], [Object] ] },
      circle: { oranges: [ [Object] ] }
    },
    { star: { bananas: [ [Object], [Object] ] } }

How would I go on and map this in a way where the unique object keys become X number of values inside an array with its combined data values matching that key.我将如何在 go 和 map 上使用唯一的 object 键成为数组中的 X 个值,其组合数据值与该键匹配。 Heres an example of what I'm trying to achieve这是我想要实现的一个例子

    const array = [
      {
        symbol: 'star',
        data: [
          { apples: [[Object], [Object]] },
          { oranges: [[Object], [Object]] },
          { bananas: [[Object], [Object]] },
        ],
      },
      {
        symbol: 'circle',
        data: [{ apples: [[Object]] }, { oranges: [[Object]] }],
      },
    ];
 

I'm assuming it would be using a reduce function and getting the keys of current value index and mapping through the keys, while checking if key exists in accumlator if not add it.我假设它将使用 reduce function 并通过键获取当前值索引和映射的键,同时检查如果不添加键是否存在于累加器中。 Haven't reached more far than this implementation/logic还没有达到比这个实现/逻辑更远的地方

Yes you said it.是的,你说过。

 const array = [ { star: { apples: [ {flag: true}, {flag: true} ] }, circle: { apples: [ {flag: true} ] } }, { star: { oranges: [ {flag: true}, {flag: true} ] }, circle: { oranges: [ {flag: true} ] } }, { star: { bananas: [ {flag: true}, {flag: true} ] } } ] var result = Object.values(array.reduce (function (agg, obj_shapes) { Object.keys(obj_shapes).forEach(function (shape) { var fruits = obj_shapes[shape] agg[shape] = agg[shape] || { symbol: shape, data: [] } agg[shape].data.push(fruits) }) return agg; }, {})); console.log(result)
 .as-console-wrapper {max-height: 100% !important}

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

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