javascript – 从任意深度的父/子关系中的所有对象中删除特定属性

我有一个JavaScript对象,表示任意深度的父子关系.如何删除所有对象的某些属性?

var persons = [{
    name: 'hans',
    age: 25,
    idontwantthis: {
      somevalue: '123'
    },
    children: [{
        name: 'hans sohn',
        age: 8,
        idontwantthiseither: {
            somevalue: '456'
        },
        children: [{
            name: 'hans enkel',
            age: 2,
            children: []
        }]
    }]
}];

我只想要属性名称,年龄和孩子,并摆脱所有其他人.新数组应如下所示:

var persons = [{
    name: 'hans',
    age: 25,
    children: [{
        name: 'hans sohn',
        age: 8,
        children: [{
            name: 'hans enkel',
            age: 2,
            children: []
        }]
    }]
}];

解决方法:

使用recursion并使用Array#forEach方法进行迭代,使用Object.keys获取属性名称数组的方法,使用delete删除对象的某些属性,使用delete进行检查是对象,使用Array.isArray进行检查是否为数组.

// hash map for storing properties which are needed to keep
// or use an array and use `indexOf` or `includes` method
// to check but better one would be an object    
var keep = {
  name: true,
  age: true,
  children: true
}


function update(obj, kp) {
  // check its an array
  if (Array.isArray(obj)) {
    // if array iterate over the elment
    obj.forEach(function(v) {
      // do recursion
      update(v, kp);
    })
  // check element is an object
  } else if (typeof obj == 'object') {
    // iterate over the object keys
    Object.keys(obj).forEach(function(k) {
      // check key is in the keep list or not
      if (!kp[k])
        // if not then delete it
        delete obj[k];
      else
        // otherwise do recursion
        update(obj[k], kp);
    })
  }
}

update(persons, keep);
var persons = [{
  name: 'hans',
  age: 25,
  idontwantthis: {
    somevalue: '123'
  },
  children: [{
    name: 'hans sohn',
    age: 8,
    idontwantthiseither: {
      somevalue: '456'
    },
    children: [{
      name: 'hans enkel',
      age: 2,
      children: []
    }]
  }]
}];

var keep = {
  name: true,
  age: true,
  children: true
}


function update(obj, kp) {
  if (Array.isArray(obj)) {
    obj.forEach(function(v) {
      update(v, kp);
    })
  } else if (typeof obj == 'object') {
    Object.keys(obj).forEach(function(k) {
      if (!kp[k])
        delete obj[k];
      else
        update(obj[k], kp);
    })
  }
}

update(persons, keep);

console.log(persons);
上一篇:javascript – Lodash / underscore:将对象数组转换为单个对象


下一篇:[Javascript] Build lodash.omitBy and lodash.pickBy with Object.fromEntries + Object.entry (isomorphi