I am trying to use the map to change the one of the field name , but I see the order of items are getting changed .
var arrOfObj = [
{
name: "test1",
value: "value1"
},
{
name: "test2",
value: "value2"
}
];
function changeKeyName(arr, oldValue, newVal) {
return arr.map(item => {
item[`${newVal}`] = item[`${oldValue}`];
delete item[`${oldValue}`];
return item;
});
}
console.log(changeKeyName(arrOfObj, "name", "type"));
Is there any way I can maintain the order of items along with changing of one of the field names.
O/P:
[{type:"test1",value: "value1"}, {type: "test2", value:"value2"}]
Thanks in advance
You can use Object.entries
to take an array of entries, then map them, replacing the old key with the new key when found:
var arrOfObj = [
{
name: "test1",
value: "value1"
},
{
name: "test2",
value: "value2"
}
];
const changeKeyName = (arr, oldKey, newKey) => arr.map(
item => Object.fromEntries(
Object.entries(item).map(
([key, val]) => [key === oldKey ? newKey : key, val]
)
)
);
console.log(changeKeyName(arrOfObj, "name", "type"));
(Contrary to popular belief, object property order is guaranteed by the specification, and has been implemented in all environments for years. But keep in mind that this will only work for keys which aren't array indicies - array indicies like 0
1
2
can't be ordered relative to other properties, they'll always be iterated over first, in ascending numeric order)
That said, code is generally easier to understand if it's written such that property order doesn't matter - if you have code that depends on the properties being in a particular order, I'd recommend refactoring it so that the property order doesn't matter.