如何检查对象数组中是否存在每个组的子元素?

时间:2017-06-30 19:55:38

标签: javascript arrays ecmascript-6

这就是我的数据结构的样子。如果每个group - 元素(如果它存在的话)都有一个子元素,我需要非常好。

所以这个例子是一个有效的数据集。如果最后一个对象丢失,它应该是无效的。组也可以嵌套。

var elements = [
    {
        "_id" : "NpxZFT4TwfDvwbtKX",
        "content" : "Group 1",
        "parent" : "bmphCpyHZLhTc74Zp",
        "type" : "group"
    },
    {
        "_id" : "zQS6pXicvXk7K2rZ4",
        "content" : "Element 1",
        "parent" : "bmphCpyHZLhTc74Zp",
        "type" : "item"
    },
    {
        "_id" : "2ct9a7xE7HTrszua7",
        "content" : "Subgroup in Group 1",
        "parent" : "NpxZFT4TwfDvwbtKX",
        "type" : "group"
    },
    {
        "_id" : "HTrszua72ct9a7xE7",
        "content" : "Element 1 in Subgroup",
        "parent" : "2ct9a7xE7HTrszua7",
        "type" : "item"
    }
]

所以我尝试过这样的事情:

elements.every(
    element => elements.some(elm => elm.parent === elm._id)
)

1 个答案:

答案 0 :(得分:0)

使用Array#reduce创建包含/不包含子项的组的地图。使用Array#every迭代地图以确定所有群组是否都有子项:

const allGroupsWithChildren = [{"_id":"NpxZFT4TwfDvwbtKX","content":"Group 1","parent":"bmphCpyHZLhTc74Zp","type":"group"},{"_id":"zQS6pXicvXk7K2rZ4","content":"Element 1","parent":"bmphCpyHZLhTc74Zp","type":"item"},{"_id":"2ct9a7xE7HTrszua7","content":"Subgroup in Group 1","parent":"NpxZFT4TwfDvwbtKX","type":"group"},{"_id":"HTrszua72ct9a7xE7","content":"Element 1 in Subgroup","parent":"2ct9a7xE7HTrszua7","type":"item"}];

const hasGroupsWithNoChildren = [{"_id":"NpxZFT4TwfDvwbtKX","content":"Group 1","parent":"bmphCpyHZLhTc74Zp","type":"group"},{"_id":"zQS6pXicvXk7K2rZ4","content":"Element 1","parent":"bmphCpyHZLhTc74Zp","type":"item"},{"_id":"2ct9a7xE7HTrszua7","content":"Subgroup in Group 1","parent":"NpxZFT4TwfDvwbtKX","type":"group"}];

const isAllWithChildren = (elements) => {
    const map = elements.reduce((map, o) => { // create map of groups
      if(o.type === 'group' && !map.has(o._id)) {
         map.set(o._id, false); // if a group doesn't exist, it  starts as childless - false
      }
      
      map.set(o.parent, true); // a child changes it's parent group has children status to true

      return map;
    }, new Map());
    
    return [...map.values()].every((value) => value); // if all map values are true, every group has at least one child
}

console.log(isAllWithChildren(allGroupsWithChildren));
console.log(isAllWithChildren(hasGroupsWithNoChildren));