如果子孙数组为空,则从对象中删除数组

时间:2020-07-07 18:54:24

标签: javascript jquery arrays javascript-objects

所以我有一个具有类似结构的对象

object.childArrays.grandchildArrays.greatgrandchildArrays

如果任何后续数组为空,我想删除子数组。 (也不能使用es6:'()

示例对象

object[
  [2019, [items, [docs, ['a', 'b', 'c']], [docs, ['d', 'e', 'f']]]], 
  [2018, [items, [docs, []]]],
  [2017, [items, [docs, ['x', 'y', 'z']]]],
]

2018年将被删除。

object[
  [2019, [items, [docs, ['a', 'b', 'c']], [docs, ['d', 'e', 'f']]]], 
  [2017, [items, [docs, ['x', 'y', 'z']]]],
]

3 个答案:

答案 0 :(得分:0)

假设“项目”和“文档”是字符串或其他某种类型的项目,则可以这样做:

function recursivelyRemoveEmptyArrays(source){
  if (Array.isArray(source)){
    const resultArray =[]
    source.forEach(oneSource=>{
      const oneResult = recursivelyRemoveEmptyArrays(oneSource);
      if (!Array.isArray(oneResult) || oneResult.length>0){
         resultArray.push(oneResult)}
      })
      return resultArray
   } else {
     return source
   }
   
}

const example=[
  [2019, ["items", ["docs", ['a', 'b', 'c']]],  ["docs", ['d', 'e', 'f']]], 
  [2018, ["items", ["docs", []]]],
  [2017, ["items", ["docs", ['x', 'y', 'z']]]],
];

console.log(recursivelyRemoveEmptyArrays(example))

但是,它不会删除“ 2018”,而只会删除深空数组:[]。 外面的数组不是空的,因为它们每个都包含一些东西,例如“文档”。

答案 1 :(得分:0)

因此,请使用一种递归方法来查看数组的所有嵌套索引是否都有数据。循环播放(如果无法将其删除)。

const items = [1];
const docs = [2];
const data = [
  [2019, [items, [docs, ['a', 'b', 'c']], [docs, ['d', 'e', 'f']]]], 
  [2018, [items, [docs, []]]],
  [2017, [items, [docs, ['x', 'y', 'z']]]],
];

var hasValues = arr => {
  return arr.every(item => {
    if (Array.isArray(item)) {
        return (item.length === 0) ? false : hasValues(item);
    } else {
      return item !== undefined; // whatever your truthy check should be
    }
  })
}

for (let i = data.length - 1; i>=0; i--) {
  if (!hasValues(data[i])) {
     data.splice(i, 1)
  }
}

console.log(data)

答案 2 :(得分:-1)

但是,如果您实际上打算让“项目”和“文档”成为对象的键,那么这就是您所需要的

在这里,我假设数据的数组部分总是从同一级别开始,即您有一个年份数字级别,在它下面是一个项目级别,在它下面是一个docs级别,并且只有在此级别内才可以具有数组。

const example = {
  2019: {
    items: {
      docs: ['a', 'b', 'c']
    }
  },
  2018: {
    items: {
      docs: []
    }
  },
  2017: {
    items: {
      docs: ['x', 'y', 'z']
    }
  },
};


const out = {}

Object.keys(example).forEach(child => { // e.g. 2019
  let nArrayItems = 0;
  Object.keys(example[child]).forEach(grandchild => {
    Object.keys(example[child][grandchild]).forEach(greatgrandchild => {
      nArrayItems += example[child][grandchild][greatgrandchild].length; // This assumes you are confident the greatgrandchild will be an array, so that you can safely rely on its length. If there is a danger that it may be a string, you should be more careful with this step.

    })
  })
  if (nArrayItems > 0) {
    out[child] = example[child]
  }
})


console.log(out)