简体   繁体   English

如何获取数组中具有相同 id 的所有 object?

[英]how to get all object that has the same id in array?

I have an array of objects and I want to re-shape them based on a similar id "itemId"我有一个对象数组,我想根据类似的 id“itemId”重新塑造它们

array = [
{"choicesId": 2, "itemId": 40, "optionChoicesId": 4},
{"choicesId": 11, "itemId": 40, "optionChoicesId": 14},
{"choicesId": 141, "itemId": 41, "optionChoicesId": 104},
{"choicesId": 311, "itemId": 41, "optionChoicesId": 1987}
];

expected array预期数组

[
  {"id":40,"selected_ids":[{"choicesId":2},{"choicesId":11}]},
  {"id":41,"selected_ids":[{"choicesId":141},{"choicesId":311}]},
  ...
]

An easy approach can be like this一个简单的方法可以是这样的

const mergeSelections = (selections) => {
  const groupedSelections = selections.reduce((acc, selection) => {
    const { itemId, choicesId } = selection;
    if (!acc[itemId]) {
      acc[itemId] = { id: itemId, selected_ids: [] };
    }
    acc[itemId].selected_ids.push({ choicesId });
    return acc;
  }, {});
  return Object.values(groupedSelections);
};

const array = [
  { choicesId: 2, itemId: 40, optionChoicesId: 4 },
  { choicesId: 11, itemId: 40, optionChoicesId: 14 },
  { choicesId: 141, itemId: 41, optionChoicesId: 104 },
  { choicesId: 311, itemId: 41, optionChoicesId: 1987 },
];

console.log(mergeSelections(array));

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

相关问题 如何检查所有特定对象在数组中是否具有相同的值? - How to check if all specific object has a same value in array? 如何从元素 id 相同的数组中获取 object - How to get an object from an array with the element id is same 如何在javascript json数组对象中获取相同id的不同值 - How to get same id different values in javascript json array object 如何使用 foreach 获取 object 数组中的所有 Id 并合并所有数据对应的 ID? - How can I get all Id in array of object by using foreach and merge the all data corresponding ID? 如果 javascript 中的 id 相同,如何合并数组中所有属性的两个对象? - How to merge two objects of all properties in an array if it has same id in javascript? 如何检查数组中的对象ID是否相同? - How to check if object id in array is the same? 我们如何从具有名称 ID 但具有特定父对象的 JSON 中获取所有属性值 - How do we get all property values from a JSON with name ID but has a specific parent object 如何获得具有相同ID的所有单选按钮? - How to get all the radio buttons with the same id? 如果hashMap具有相同的键名,如何获取对象数组中的所有值 - How do I get all values in array of objects if hashMap has same key name 如何将不同的属性合并到具有相同 id 的 object 中? - How to merge different properties into an object which has same id?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM