I am working with a array of objects and i need to add property 'orderTemp' to each of the objects based on temp value where i don't need to change the order of objects
My initial array of objects looks like so
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23 },
...
];
So my resulting array of objects would look something like so
[
{ humidity: 95, location: 'Konstanz', pressure: 1003, temp: 22.46, orderTemp: 2 },
{ humidity: 45, location: 'India', pressure: 1014, temp: 2.23, orderTemp: 1 },
...
];
CodePudding user response:
You can do something like this:
// 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)
})
);