如何根据临时值将 属性 添加到每个对象,但不更改对象的顺序
how to add property to each of the objects based on temp value ,but don't change the order of objects
我正在处理一组对象,我需要根据临时值向每个对象添加 属性 'orderTemp',而我不需要更改对象的顺序
我的初始对象数组看起来像这样
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23 },
...
];
所以我得到的对象数组看起来像这样
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46, orderTemp: 2 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23, orderTemp: 1 },
...
];
你可以这样做:
// get list of all temperature values and sort it
const temperatures = data.map(item => item.temp).sort();
// if you want to change source data
data.forEach(item => item.orderTemp = temperatures.indexOf(item.temp));
// if you want create new array with this additional field in object
const newData = data.map(item => ({
...item,
orderTemp: temperatures.indexOf(item.temp)
})
);
我正在处理一组对象,我需要根据临时值向每个对象添加 属性 'orderTemp',而我不需要更改对象的顺序
我的初始对象数组看起来像这样
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23 },
...
];
所以我得到的对象数组看起来像这样
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46, orderTemp: 2 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23, orderTemp: 1 },
...
];
你可以这样做:
// get list of all temperature values and sort it
const temperatures = data.map(item => item.temp).sort();
// if you want to change source data
data.forEach(item => item.orderTemp = temperatures.indexOf(item.temp));
// if you want create new array with this additional field in object
const newData = data.map(item => ({
...item,
orderTemp: temperatures.indexOf(item.temp)
})
);