How to replace array element value with another
i have array like this, without using jquery
this.products = [
{
text: 'prod1',
value: 1
},
{
text: 'prod2',
value: 2
},
{
text: 'prod3',
value: 3
}
];
i want to replace 'text' to 'label'
How to replace array element value with another
i have array like this, without using jquery
this.products = [
{
text: 'prod1',
value: 1
},
{
text: 'prod2',
value: 2
},
{
text: 'prod3',
value: 3
}
];
i want to replace 'text' to 'label'
Share Improve this question edited Dec 4, 2017 at 13:02 SALEH 1,5621 gold badge14 silver badges22 bronze badges asked Dec 4, 2017 at 11:55 SrinuSrinu 1512 gold badges2 silver badges11 bronze badges 4 |4 Answers
Reset to default 13How about this?
var products = [{
text: 'prod1',
value: 1
},
{
text: 'prod2',
value: 2
}, {
text: 'prod3',
value: 3
}
];
products.forEach(function(obj) {
obj.label = obj.text;
delete obj.text;
});
console.log(products);
using ES6:
const updatedProducts = products.map(({text: label, value})=>({value, label}));
There are many ways using map in ES6
var products = [
{
text: 'prod1',
value: 1
},
{
text: 'prod2',
value: 2
},
{
text: 'prod3',
value: 3
}
];
const newProducts = products.map(({text: label, value})=>({value, label}));
console.log(newProducts );
console.log("===================Another Method====================")
products.map((el)=>{
el.label = el.text
delete el.text
})
console.log(products);
For people like me who are looking for an answer that does not mutate the original objects (which will cause errors in React) but instead want to return a new array full of new objects with only one specific key renamed in each object I have create the following function.
export const renameKey = (arr, oldKey, newKey) => {
let newArray = [];
arr.forEach((obj) => {
let newObj = {};
const keys = Object.keys(obj);
keys.forEach((key) => {
if (key === oldKey) {
Object.assign(newObj,{ [newKey]: obj[oldKey] });
} else {
Object.assign(newObj,{ [key]: obj[key] });
}
});
newArray.push(newObj);
});
return newArray;
};
products.map(prod => { return { label: prod.text, value: prod.value }; })
– haim770 Commented Dec 4, 2017 at 11:58var result = products.map(({text, value}) => ({label: text, value}));
– Hassan Imam Commented Dec 4, 2017 at 12:16