繁体   English   中英

如何在不在 object 中创建 object 的情况下将新旧对象合并到一个数组中?

[英]How can i merge old and new objects in one array without creating an object inside object?

const array = [{
  "id": "1",
  "main": [{
    "type": "a",
    "nu": '0',
    "role": 1
  }],
}, {
  "id": "2",
  "main": [{
    "type": "b",
    "nu": '0',
    "role": 2
  }],
}, {
  "id": "3",
  "main": [{
    "type": "c",
    "nu": '0',
    "role": 2
  }],
}, {
  "id": "4",
  "main": [{
    "type": "d",
    "nu": '0',
    "role": 2
  }],
}]

从上面的 object,我想将 id- 2,3 和 4 组合成一个具有 3 个对象的键。

const result = [array.reduce((acc, {id, main}) => {
  const { nu, role, type } = main[0]
  const hash = `${nu}-${role}`;
  acc[hash] = acc[hash] ? [{ ...acc[hash] }, {type: type, id: id }] : 
{ type, id: [id] };
  return acc;
}, {})];

预期的:

例子:

 const array = [{ "id": "1", "main": [{ "type": "a", "nu": '0', "role": 1 }], }, { "id": "2", "main": [{ "type": "b", "nu": '0', "role": 2 }], }, { "id": "3", "main": [{ "type": "c", "nu": '0', "role": 2 }], }, { "id": "4", "main": [{ "type": "d", "nu": '0', "role": 2 }], }] const result = [array.reduce((acc, {id, main}) => { const { nu, role, type } = main[0] const hash = `${nu}-${role}`; acc[hash] = acc[hash]? [{...acc[hash] }, {type: type, id: id }]: { type, id: [id] }; return acc; }, {})]; console.log(result);

我不确定我哪里出错了,有人可以帮忙吗?

您可以将 arrays 减少为 object 和一个在开始时用零填充的公共密钥。

 const data = [{ id: "1", main: [{ type: "a", nu: "0", role: 1 }] }, { id: "2", main: [{ type: "b", nu: "0", role: 2 }] }, { id: "3", main: [{ type: "c", nu: "0", role: 2 }] }, { id: "4", main: [{ type: "d", nu: "0", role: 2 }] }], result = data.reduce((r, { id, main }) => { main.forEach(({ type, nu, role }) => { const key = `${nu.toString().padStart(3, 0)}-${role}`; (r[key]??= []).push({ id, type }); }); return r; }, {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

为了获得准确的结果,如图所示,您可以将一个组的第一个 object 的id包装在一个数组中,如果一个组有多个 object,则采用一个数组。

 const data = [{ id: "1", main: [{ type: "a", nu: "0", role: 1 }] }, { id: "2", main: [{ type: "b", nu: "0", role: 2 }] }, { id: "3", main: [{ type: "c", nu: "0", role: 2 }] }, { id: "4", main: [{ type: "d", nu: "0", role: 2 }] }], result = data.reduce((r, { id, main }) => { main.forEach(({ type, nu, role }) => { const key = `${nu.toString().padStart(3, 0)}-${role}`; r[key] = r[key]? [].concat(r[key], { id, type }): { id: [id], type }; }); return r; }, {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暂无
暂无

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

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