[英]How to remove an element from an array using _.set or equivalent
How to remove an element using lodash/fp's set
or equivalent method.如何使用 lodash/fp 的
set
或等效方法删除元素。
I tried我试过了
_.set({data:[1,2,3]},"data[1]", undefined)
which results in {data:[1,undefined,3]}
where as I would like to get the output as {data:[1,3]}
这导致
{data:[1,undefined,3]}
我想将 output 作为{data:[1,3]}
also tried unset
which results in {data:[1,empty,3]}
还尝试了
unset
导致{data:[1,empty,3]}
Here is a clean solution for you.这是一个干净的解决方案。 The only thing you need to change is the
_.isEqual(idx, 1)
for whatever index that you want to remove, or even change it and use an array, if you need by using _.includes([1, 5, 10], idx)
instead of the _.isEqual()
functionality.您唯一需要更改的是
_.isEqual(idx, 1)
用于您要删除的任何索引,或者甚至更改它并使用数组,如果您需要使用_.includes([1, 5, 10], idx)
而不是_.isEqual()
功能。
// Your idea: _.set({data:[1,2,3]},"data[1]", undefined) // Using a simple _.reject() function: const newData = _.assign({}, myObj, { data: _.reject(myObj.data, (val, idx) => _.isEqual(idx, 1)) });
I solved it using a sequence of operations.我使用一系列操作解决了它。
get
to fetch the array at the specified path.get
获取指定路径的数组。slice
to get a sliced array till specified index.slice
得到一个切片数组,直到指定索引。slice
to get second array after specified index.slice
在指定索引后获取第二个数组。concat
to merge first and second array.concat
合并第一个和第二个数组。set
to set the array at the specified path.set
将数组设置在指定路径。 const arrayData = get(path, state);
if (arrayData && index < arrayData.length) {
const firstSet = slice(0, payload.index, arrayData);
console.log("array data after slice", arrayData);
const secondSet = slice(payload.index + 1, arrayData.length, arrayData);
const newState = set(
path,
concat(firstSet, secondSet),
state
);
} else {
return {...state}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.