Lodash:如何使用ID从数组中删除项目或嵌套项目?

时间:2019-02-26 12:29:10

标签: javascript arrays multidimensional-array lodash

我有一个如下所示的数组:

[
    {
        "id": "denuzi",
        "sub":
        [
            {"id": "s4p58o"},
            {"id": "xzbqi"},
        ],
    },
    {
        "id": "4rcodm",
        "sub": [],
    }
]

我想做的是使用提供的ID从数组或嵌套数组中删除一项。

例如如果提供了denuzi,则整个第一个对象都将被删除;如果提供了s4p58o,则只删除了第一个对象子数组中的那个对象。

我知道我可以使用以下代码删除整个对象:

_.remove(this.items, function(item) {
    return item.id !== id;
});

但是我不确定如何检查删除子项目吗?

3 个答案:

答案 0 :(得分:1)

您可以通过检查id来采取迭代和递归的方法,或者再次调用sub。找到后退出。

function remove(array, id) {
    return array.some((o, i, a) => o.id === id
        ? a.splice(i, 1)
        : remove(o.sub || [], id)
    );
}

var array = [{ id: "denuzi", sub: [{ id: "s4p58o" }, { id: "xzbqi" }] }, { id: "4rcodm", sub: [] }];

remove(array, 's4p58o');
console.log(array);

remove(array, 'denuzi');
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

只需使用Array.prototype.filter

var list = [
    {
        "id": "denuzi",
        "sub":
        [
            {"id": "s4p58o"},
            {"id": "xzbqi"},
        ],
    },
    {
        "id": "4rcodm",
        "sub": [],
    }
]

const result = list.filter(a => a.id !== 'denuzi');

console.log(result);

答案 2 :(得分:0)

不使用lodash

const data = [
    {
        "id": "denuzi",
        "sub":
        [
            {"id": "s4p58o"},
            {"id": "xzbqi"},
        ],
    },
    {
        "id": "4rcodm",
        "sub": [],
    }
]


function remove(data, removeId){
  return _.remove(data, (item) => item.id !== removeId)  // removes parent object if its id matches removeId
    .map(({id, sub}) => ({id, sub: _.remove(sub, (item) => item.id !== removeId)})) // replaces sub array with new sub array with subobject missing
}

// i parse data to do a deep copy for showing the property
console.log(remove(JSON.parse(JSON.stringify(data)), "s4p58o")); 
console.log(remove(JSON.parse(JSON.stringify(data)), "denuzi"))

与lodash

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
{{1}}