繁体   English   中英

如何替换两个 arrays 对象的 object 中的键/值对

[英]How to replace key/value pairs in an object of two arrays of objects

我想将键 'id' 和它的值替换为 'type' 的属性,其值为 'inc' 或 'exp'。 我还想从 exp 数组中的对象中删除属性“百分比”。 最后,我想将所有对象合并到一个数组中。

这就是我所做的,它具有预期的结果,但必须有一条捷径来实现这一目标,代码更少,更干净。 谢谢!

const list = {
     exp: [
       { id: 0, value: 57, percentage: 12 },
       { id: 1, value: 34, percentage: 10 },
    ],
     inc: [
       { id: 1, value: 18 },
       { id: 1, value: 89 },
    ],
};

// Deep copy of list object
let newList = JSON.parse(JSON.stringify(list));

// Destructuring
const { exp, inc } = newList;

for (let obj of exp) {
  obj.type = "exp";
  delete obj.id;
  delete obj.percentage;
}

for (let obj2 of inc) {
  obj2.type = "inc";
  delete obj2.id;
}

//Spread operator
newList = [...newList.exp, ...newList.inc];
console.log(newList);


 

您可以在Object.entries()的支持下使用flatMap

 const list = { exp: [ { id: 0, value: 57, percentage: 12 }, { id: 1, value: 34, percentage: 10 }, ], inc: [ { id: 1, value: 18 }, { id: 1, value: 89 }, ], }; const res = Object.entries(list).flatMap(([type, values]) => values.map((value) => ({ value: value.value, type: type, })) ); console.log(res);

一步步

A = Object.entries(list)

// -->

[
  [
    "exp",
    [
      { "id": 0, "value": 57, "percentage": 12 },
      { "id": 1, "value": 34, "percentage": 10 }
    ]
  ],
  [
    "inc",
    [
      { "id": 1, "value": 18 },
      { "id": 1, "value": 89 }
    ]
  ]
]
B = A.map(...)

// -->

[
  [
    { "value": 57, "type": "exp" },
    { "value": 34, "type": "exp" }
  ],
  [
    { "value": 18, "type": "inc" },
    { "value": 89, "type": "inc" }
  ]
]
C = B.flat()

// -->

[
  { "value": 57, "type": "exp" },
  { "value": 34, "type": "exp" },
  { "value": 18, "type": "inc" },
  { "value": 89, "type": "inc" }
]

flatMap是步骤 B 和 C 的组合( .map然后.flat

如果value是您想要的唯一属性:

 const list = { exp: [ { id: 0, value: 57, percentage: 12 }, { id: 1, value: 34, percentage: 10 } ], inc: [ { id: 1, value: 18 }, { id: 1, value: 89 } ] }; const newList = []; const types = Object.keys(list); types.forEach((type) => { list[type].forEach(({ value }) => { newList.push({ type, value }); }); }); console.log(newList); console.log(JSON.stringify(newList));

暂无
暂无

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

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