I want to add a key and value(i.e. age:15) to an object which has name as email and remove it(age) from other objects for the below array of object.
[
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
]
i.e. I want the below output.
[
{
name: 'test',
lname: 'last'
},
{
name: 'test1',
lname: 'last1'
},
{
name: 'email',
lname: 'last',
age: 15
},
]
Thanks
CodePudding user response:
What you can do here is find the index of the object that has name
as "email". Once you find the object, add the desired age value as a new property called age
. Finally, you can use filter
to filter the items that doesn't have name
as "email" and delete the age
property.
var data = [ { name: 'test', lname: 'last', age: 5 }, { name: 'test1', lname: 'last1', age: 15 }, { name: 'email', lname: 'last', }, ]
function myFunction(age) {
let indexOfEmail = data.findIndex(element => element.name == "email")
if (indexOfEmail > -1) {
data[indexOfEmail].age = age
data.filter(element => element.name !== "email").map(sub => delete sub['age'])
}
}
myFunction(15)
console.log(data)
CodePudding user response:
You can do it by using map
method, like this:
const data = [
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
];
const newData = data.map(({age, ...rest})=> rest.name == 'email' ? {...rest, age: 15} : rest)
console.log(newData);
CodePudding user response:
You can do like this:
const items = [
{
name: 'test',
lname: 'last',
age: 5
},
{
name: 'test1',
lname: 'last1',
age: 15
},
{
name: 'email',
lname: 'last',
},
];
const newItems = items.filter((item) => {
if (item.name.includes("email")) {
return (item.age = 15);
}
if (JSON.stringify(items).includes("email")) {
delete item.age;
}
return item;
});
console.log(newItems);