如何替换两个对象数组的对象中的键/值对

时间:2021-01-08 07:53:24

标签: javascript object

我想用值为“inc”或“exp”的“type”属性替换键“id”及其值。我还想从 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);


 

2 个答案:

答案 0 :(得分:2)

您可以使用 flatMap 来支持 Object.entries()

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

答案 1 :(得分:1)

如果 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));