将对象数组与数组值合并为单个对象

huangapple go评论72阅读模式
英文:

Merge array of objects with array values into a single object

问题

使用纯JavaScript或lodash,将对象数组转换为单个对象并连接任何数组值的最简单方法是什么?

我可以使用_.flatMap(before, "nodes")来处理单个属性,但不确定如何包含所有属性。

例如:

const before = [
  {
    nodes: [
      { "id": "1" },
      { "id": "2" }
    ],
    links: [
      { "source": "1", "target": "2" }
    ],
  },
  {
    nodes: [
      { "id": "3" },
      { "id": "4" },
      { "id": "5" },
      { "id": "6" }
    ],
    links: [
      { "source": "3", "target": "4" },
      { "source": "5", "target": "6" }
    ],
  }
];

const after = {
  nodes: [
    { "id": "1" },
    { "id": "2" },
    { "id": "3" },
    { "id": "4" },
    { "id": "5" },
    { "id": "6" }
  ],
  links: [
    { "source": "1", "target": "2" },
    { "source": "3", "target": "4" },
    { "source": "5", "target": "6" }
  ],
};

请注意,上述代码示例是JavaScript代码,不需要翻译。

英文:

Using plain JavaScript or lodash, what's the easiest way to transform an array of objects into a single object, while concatenating any array values?

I can achieve it on a single property using _.flatMap(before, "nodes") but not sure how to include all properties.

For example:

const before = [
  {
    nodes: [
      { "id": "1" },
      { "id": "2" }
    ],
    links: [
      { "source": "1", "target": "2" }
    ],
  },
  {
    nodes: [
        { "id": "3" },
        { "id": "4" },
        { "id": "5" },
        { "id": "6" }
    ],
    links: [
      { "source": "3", "target": "4" },
      { "source": "5", "target": "6" }
    ],
  }
];

const after = {
  nodes: [
    { "id": "1" },
    { "id": "2" },
    { "id": "3" },
    { "id": "4" },
    { "id": "5" },
    { "id": "6" }
  ],
  links: [
    { "source": "1", "target": "2" },
    { "source": "3", "target": "4" },
    { "source": "5", "target": "6" }
  ],
};

答案1

得分: 1

你可以使用普通的JavaScript(vanilla JS)来实现这个,使用 reduceObject.entries,代码如下:

const before = [
    {
        nodes: [
            { "id": "1" },
            { "id": "2" }
        ],
        links: [
            { "source": "1", "target": "2" }
        ],
    },
    {
        nodes: [
            { "id": "3" },
            { "id": "4" },
            { "id": "5" },
            { "id": "6" }
        ],
        links: [
            { "source": "3", "target": "4" },
            { "source": "5", "target": "6" }
        ],
    }
];

const result = before.reduce((acc, curr) => {
    Object.entries(curr).forEach(([key, value]) => {
        acc[key] = [ ...(acc[key] ?? []), ...value];
    })
    return acc;
}, {});

console.log(result);
英文:

You can achieve this using vanilla js using reduce and Object.entries as:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const before = [
    {
        nodes: [
            { &quot;id&quot;: &quot;1&quot; },
            { &quot;id&quot;: &quot;2&quot; }
        ],
        links: [
            { &quot;source&quot;: &quot;1&quot;, &quot;target&quot;: &quot;2&quot; }
        ],
    },
    {
        nodes: [
            { &quot;id&quot;: &quot;3&quot; },
            { &quot;id&quot;: &quot;4&quot; },
            { &quot;id&quot;: &quot;5&quot; },
            { &quot;id&quot;: &quot;6&quot; }
        ],
        links: [
            { &quot;source&quot;: &quot;3&quot;, &quot;target&quot;: &quot;4&quot; },
            { &quot;source&quot;: &quot;5&quot;, &quot;target&quot;: &quot;6&quot; }
        ],
    }
];

const result = before.reduce((acc, curr) =&gt; {
    Object.entries(curr).forEach(([key, value]) =&gt; {
        acc[key] = [ ...(acc[key] ?? []), ...value];
    })
    return acc;
}, {});

console.log(result);

<!-- end snippet -->

答案2

得分: 1

由于您想将数组合并为一个数组,应该使用 reduce 而不是 map。以下代码应该有效:

after = before.reduce((prevResult, element) => {
    var newResult = {}
    Object.keys(element).forEach((key) => {
        newResult[key] = prevResult[key].concat(element[key])
    })
    return newResult
})

reduce 将按从左到右的迭代方式处理每个元素。

希望这有所帮助。

英文:

Since you want to merge array into one, you should use reduce instead of map. Following should work

after = before.reduce((prevResult, element) =&gt; {
    var newResult = {}
    Object.keys(element).forEach((key) =&gt; {
        newResult[key] = prevResult[key].concat(element[key])
    })
    return newResult
})

reduce will work with each element in iterative manner from left to right.

Hope this helps

答案3

得分: 1

使用lodash的一个可能解决方案:

const after = _.reduce(before, (acc, curr) => {
  _.forOwn(curr, (value, key) => {
    acc[key] = _.concat(acc[key] || [], value);
  });
  
  return acc;
}, {});

结果是一个包含这些合并数组的新对象。

英文:

One possible solution using lodash:

const after = _.reduce(before, (acc, curr) =&gt; {
  _.forOwn(curr, (value, key) =&gt; {
    acc[key] = _.concat(acc[key] || [], value);
  });
  
  return acc;
}, {});

The result is a new object that contains these combined arrays.

答案4

得分: 1

const before = [
  {
    nodes: [
      { "id": "1" },
      { "id": "2" }
    ],
    links: [
      { "source": "1", "target": "2" }
    ],
  },
  {
    nodes: [
      { "id": "3" },
      { "id": "4" },
      { "id": "5" },
      { "id": "6" }
    ],
    links: [
      { "source": "3", "target": "4" },
      { "source": "5", "target": "6" }
    ],
  }
];

Following below code:
```javascript
const flatData = (data) => {
    const result = { nodes : [], links: [] };

    for (let i = 0; i < data.length; i++) {
        const {nodes, links} = data[i]; // nodes and links

        // nodes
        for (let i = 0; i < nodes.length; i++) {
            result.nodes = [...result.nodes, nodes[i]];
        }

        // links
        for (let i = 0; i < links.length; i++) {
            result.links = [...result.links, nodes[i]];
        }
    }

    return result;
}
英文:
const before = [
  {
    nodes: [
      { &quot;id&quot;: &quot;1&quot; },
      { &quot;id&quot;: &quot;2&quot; }
    ],
    links: [
      { &quot;source&quot;: &quot;1&quot;, &quot;target&quot;: &quot;2&quot; }
    ],
  },
  {
    nodes: [
        { &quot;id&quot;: &quot;3&quot; },
        { &quot;id&quot;: &quot;4&quot; },
        { &quot;id&quot;: &quot;5&quot; },
        { &quot;id&quot;: &quot;6&quot; }
    ],
    links: [
      { &quot;source&quot;: &quot;3&quot;, &quot;target&quot;: &quot;4&quot; },
      { &quot;source&quot;: &quot;5&quot;, &quot;target&quot;: &quot;6&quot; }
    ],
  }
];

Following below code:

const flatData = (data) =&gt; {
    const result = { nodes : [], links: [] };

    for (let i = 0; i &lt; data.length; i++) {
        const {nodes, links} = data[i]; // nodes and links

        // nodes
        for (let i = 0; i &lt; nodes.length; i++) {
            result.nodes = [...result.nodes, nodes[i]];
        }

        // links
        for (let i = 0; i &lt; links.length; i++) {
            result.links = [...result.links, nodes[i]];
        }
    }

    return result;
}

答案5

得分: 1

你可以使用 Array.reduce() 来高效地实现这个目标。

请查看以下代码:

const before = [{
    nodes: [{
        "id": "1"
      },
      {
        "id": "2"
      }
    ],
    links: [{
      "source": "1",
      "target": "2"
    }],
  },
  {
    nodes: [{
        "id": "3"
      },
      {
        "id": "4"
      },
      {
        "id": "5"
      },
      {
        "id": "6"
      }
    ],
    links: [{
        "source": "3",
        "target": "4"
      },
      {
        "source": "5",
        "target": "6"
      }
    ],
  }
];

const after = before.reduce((acc, curr) => {
    Object.keys(curr).forEach(key => {
        acc[key] = [...acc[key], ...curr[key]]
    })
    return acc;
})
console.log("After is ===>>", after);

(注意:以上内容为代码示例的翻译,不包含其他内容。)

英文:

You can use Array.reduce() to achieve this efficiently.

Please find the following code:

<!-- begin snippet: js hide false console: true babel: false -->

<!-- language: lang-js -->

const before = [{
    nodes: [{
        &quot;id&quot;: &quot;1&quot;
      },
      {
        &quot;id&quot;: &quot;2&quot;
      }
    ],
    links: [{
      &quot;source&quot;: &quot;1&quot;,
      &quot;target&quot;: &quot;2&quot;
    }],
  },
  {
    nodes: [{
        &quot;id&quot;: &quot;3&quot;
      },
      {
        &quot;id&quot;: &quot;4&quot;
      },
      {
        &quot;id&quot;: &quot;5&quot;
      },
      {
        &quot;id&quot;: &quot;6&quot;
      }
    ],
    links: [{
        &quot;source&quot;: &quot;3&quot;,
        &quot;target&quot;: &quot;4&quot;
      },
      {
        &quot;source&quot;: &quot;5&quot;,
        &quot;target&quot;: &quot;6&quot;
      }
    ],
  }
];

const after = before.reduce((acc, curr) =&gt; {
    Object.keys(curr).forEach(key =&gt; {
        acc[key] = [...acc[key] , ...curr[key]]
    })
    return acc;
})
console.log(&quot;After is ===&gt;&gt;&quot;, after);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月19日 13:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定