将对象的键和子值相互配对以形成对象数组

时间:2019-04-24 17:09:39

标签: javascript arrays object

我有一个尝试重新排列的对象数组。

我尝试将Object.keys()Object.values().map()组合使用,但是找不到解决方法。

let samples = [
  {
    Nitrogen: { units: "mg/L", value: 2 },
    Phosphorus: { units: "mg/L", value: 4 }
  }, {
    Nitrogen: { units: "mg/L", value: 2 },
    Phosphorus: { units: "mg/L", value: 4 }
  }
]

希望获取数组中每个项目的子值并将其上移一个级别。

预期结果:

let samplesValues = [
  { Nitrogen: 2, Phosphorus: 4 },
  { Nitrogen: 2, Phosphorus: 4 }
]

2 个答案:

答案 0 :(得分:2)

您可以map遍历数组,reduce遍历每个对象。

const samples = [{Nitrogen: {units: "mg/L", value: 2}, Phosphorus: {units: "mg/L", value: 4}}, {Nitrogen: {units: "mg/L", value: 2}, Phosphorus: {units: "mg/L", value: 4}}];

const out = samples.map(obj => {
  const keys = Object.keys(obj);
  return keys.reduce((acc, key) => {
    const { value } = obj[key];
    return {...acc, [key]: value };
  }, {});
});

console.log(out);

编辑:是的,这是一个很巧妙的技巧。您只需为value分配默认值obj[key]

const samples = [{sampleID: 1, Nitrogen: {units: "mg/L", value: 2}, Phosphorus: {units: "mg/L", value: 4}}, {sampleID: 2, Nitrogen: {units: "mg/L", value: 2}, Phosphorus: {units: "mg/L", value: 4}}];

const out = samples.map(obj => {
  const keys = Object.keys(obj);
  return keys.reduce((acc, key) => {
    const { value = obj[key] } = obj[key];
    return {...acc, [key]: value };
  }, {});
});

console.log(out);

答案 1 :(得分:0)

在使用map并将变量返回为key时,请始终使用[key]

let samples = [{
  Nitrogen: {
    units: "mg/L",
    value: 2
  },
  Phosphorus: {
    units: "mg/L",
    value: 4
  }
}, {
  Nitrogen: {
    units: "mg/L",
    value: 2
  },
  Phosphorus: {
    units: "mg/L",
    value: 4
  }
}]

let sampleValues = samples.map(sample => {
  const keys = Object.keys(sample);
  return keys.map(key => {
    return {
      [key]: sample[key].value
    };
  });
})


console.log(sampleValues);