简体   繁体   中英

Remove all keys with a same name from array of object

I have a array of Javascript objects, and I want to clear all the key-value pairs where the name of the key is id . How can I do this?

Example input:

var s = [{
  items:[{
    id: 1,
    items:[{
      items:[{
        id: 2,
        items:[]
      }]
    }]
  }],
  id: 3
}]

Example output:

var s = [{
  items:[{
    items:[{
      items:[{
        items:[]
      }]
    }]
  }]
}]

You could make use of a recursive function like this:

function removeKey(obj, searchKey) {
  for(objKey in obj) {
    if (objKey === searchKey)
      delete obj[objKey];
    else if (typeof obj[objKey] === 'object')
      removeKey(obj[objKey], searchKey);
  }
}

removeKey(yourObj, 'id')

Example: http://jsfiddle.net/bsnfqkL9/3/

You could beautify the iteration using a generator:

 function* flattenItems(items) {
  for(const item of items) {
    yield item;
    yield* flattenItems(item.items);
  }
}

So then your task is pretty simple:

 for(const item of flattenItems(s))
   delete item.id;

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