简体   繁体   中英

How to remove a simple specific key value pair from all objects and add to one specific object inside an array

I want to add a key and value(ie 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',
  },
]

ie I want the below output.

[
  {
    name: 'test',
    lname: 'last'
  },
  {
    name: 'test1',
    lname: 'last1'
  },
  {
    name: 'email',
    lname: 'last',
    age: 15
  },
]

Thanks

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)

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM