使用lodash中的嵌套属性从数组中删除对象

时间:2017-03-13 22:26:38

标签: javascript lodash

我有这个数组:

sudo xcode-select -s /Applications/Xcode.app

我正在尝试使用lodash删除var myArray = [{state: {name: 'object #1'}}, {state: {name: 'object #2'}}, {state: {name: 'object #3'}}]; 'object#1'的对象。目前我这样做:

state.name

但它不起作用。最初我尝试过这样,对我来说这是更明显的做法:

_.remove(myArray, {
        name: 'object #1'
    });

但它也没有用,我的JS验证器抱怨那里的点符号。

你如何在lodash中这样做?

6 个答案:

答案 0 :(得分:4)

File file = new Java.IO.File("/sdcard/Movies/videoFile.mp4"); videoPanel.setVideoPath(file.getAbsolutePath()); 采用谓词函数。 你可以这样做:

_.remove

答案 1 :(得分:3)

在纯粹的js中,使用Array#filter



var myArray = [{state: {name: 'object #1'}},
               {state: {name: 'object #2'}},
               {state: {name: 'object #3'}}];

    myArray = myArray.filter(v => v.state.name != 'object #1');
    console.log(myArray);




或使用Array#forEach



var myArray = [{state: {name: 'object #1'}},
               {state: {name: 'object #2'}},
               {state: {name: 'object #3'}}],
    newArr = [];
    myArray.forEach(v => v.state.name !== 'object #1' ? newArr.push(v) : null);
    console.log(newArr);




答案 2 :(得分:2)

如果要求从现有数组中删除元素,您可以使用Array.prototype.splice()Array.prototype.findIndex()



var myArray = [{state: {name: 'object #1'}},
               {state: {name: 'object #2'}},
               {state: {name: 'object #3'}}];

myArray.splice(myArray.findIndex(({state:{name}}) => name === "object #1"), 1);

console.log(myArray);




答案 3 :(得分:2)

您可以使用lodash rejectmatchesProperty简写。

var result = _.reject(myArray, ['state.name', 'object #1']);

var myArray = [{
    state: {
      name: 'object #1'
    }
  },
  {
    state: {
      name: 'object #2'
    }
  },
  {
    state: {
      name: 'object #3'
    }
  }
];

var result = _.reject(myArray, ['state.name', 'object #1']);

console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

答案 4 :(得分:1)

你可以使用_.remove这样的回调:

_.remove(myArray, function(o) {
    return o.name === 'object #1';
});

或短暂使用箭头功能,如下所示:

_.remove(myArray, o => o.name === 'object #1');

答案 5 :(得分:1)

为什么要使用lodash,当你可以在计划JS中做到这一点?

await client.execute(function() {
            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$ucNCDList$ucPagination$nextPage', '', true, '', '', false, true));
        });