我有一个尝试重新排列的对象数组。
我尝试将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 }
]
答案 0 :(得分:2)
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);