[enter image description here][1] I have an object like this and I have to remove '_demo' in each item I tired below it did not work!
here is the image! [1]: https://i.stack.imgur.com/krIGK.png
datalist.forEach((data)=>{
for(let da in data){
da.replace('_demo','')
}
})
CodePudding user response:
You can't change the name of an existing key, Either you delete the old key and create a new key with its value, or create a new object with the new key instead of the old key.
datalist = datalist.map(({ "test No_demo": test, ...data })=>{
return {
...data,
"test No": test
}
})
CodePudding user response:
Since you can't directly alter an object's key: if the object key includes
"_demo" create a new key, assign the value of the old object property to the new property defined by the new key, and then delete the old property.
const obj = {
a_demo: 1,
b: 2,
c_demo: 3
};
for (const key in obj) {
if (key.includes('_demo')) {
const newKey = key.replace('_demo', '');
obj[newKey] = obj[key];
delete obj[key];
}
}
console.log(obj);
CodePudding user response:
Using Object.keys
to map each key and replace the _demo
part.
let datalist = [
{
"Index": "312",
"test No_demo": "skjhksdjhfsh",
"Date created": "26/06/2018",
"Updateddate_demo": "26/06/2018",
"Address_demo": "testing"
},
{
"Index": "312",
"test No_demo": "skjhksdjhfsh",
"Date created": "26/06/2018",
"Updateddate_demo": "26/06/2018",
"Address_demo": "testing"
}
]
let res = datalist.map(row => {
let x = {}
Object.keys(row).map( k => {
x[k.replace('_demo', '')] = row[k]
});
return x
});
console.log(res)