繁体   English   中英

根据对象属性和值弹出数组元素

[英]Pop array element based on object property and value

我想知道如何通过对象的属性和值从数组中提取单个对象,如下所示:

let arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}]
let Obj = arr.pop({night:true})
// obj: {temp:12, night: true}
// arr now: [{temp:36, night: false}, {temp:24, night: true}]

有什么建议吗?

编写自己的函数,迭代目标数组,然后拼接到新数组

function removeElements(arr, prop, value) {
    let poppedElems = [];
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i].hasOwnProperty(prop) && arr[i][prop] === value) {
            poppedElems = poppedElems.concat(arr.splice(i, 1));
        }
    }

    return poppedElems
}

如果您只想要第一个:

function findElement(arr, prop, value) {
    let elem = null;
    let elemIndex = arr.findIndex(x => x.hasOwnProperty(prop) && x[prop] === value);

    if (elemIndex !== -1) {
        elem = arr.splice(elemIndex, 1)[0];
    }         

    return elem;
}
  1. 循环播放
  2. 检查物业价值
  3. 使用splice将其从数组中移除并中断循环

 let arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}], test = {night:true}; required = null; function doTheStuff(obj, arr){ for(var i=0; i<arr.length; i++){ if(arr[i].night == test.night){ required = arr[i] arr.splice(i,1); break; } } } doTheStuff(test,arr) console.log("required" , required) console.log("arr", arr) 

使用以下数组:

let arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}];

最简单的方法是使用findIndex()方法。

返回Night为false的第一个元素:

let index = arr.findIndex(elem => !elem.night);
// index = 0

返回true的第一个元素:

let index = arr.findIndex(elem => elem.night)
// index = 1

然后获取元素:

let obj = arr[index];

您可能会想使用findIndex ,它找到满足提供的测试功能的第一个元素的索引。 find也可以,但是您不知道它在数组中的位置,因此您无法删除它。 bind允许您将参数传递给findMatch ,因此您可以选择属性和搜索值,而无需编写更多函数。

一个有效的例子是

arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}];
config = {
    propName: "night",
    propVal: true
};
function findMatch(elt) {
    return elt[this.propName] == this.propVal;
}
ind = arr.findIndex(findMatch.bind(config));
elt = arr[ind];
arr.splice(ind, 1); //Delete 1 element at position ind

find night: false获得第一个的方法night: false

let arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}]
arr = arr.find(a => !a.night)
console.log(JSON.stringify(arr))

最初误解了这个问题。 修改后的答案尽可能简洁:

var arr = [{temp:36, night: false}, {temp:12, night: true}, {temp:24, night: true}];
let obj;

var key = 'night';
var value = true;


for(var item in arr){
  if(arr[item][key]==value){
    obj = arr[item];
    arr.splice(item,1);
    break;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM