使用新值更新现有JS关联数组

时间:2017-11-21 07:26:05

标签: javascript arrays

我想在下面的数组中搜索 3.30pm ,并在JS中更新数组索引的类型

0: {time: "2:00pm",type:16}
1: {time: "3:30pm",type:30}
2: {time: "5:00pm",type:90}

任何人请建议正确的解决方法。

我试过了..

 function in_array(array, id) {
    console.log(array);
    for(var i=0;i<array.length;i++) {
        return (array[i][0].time === id)
    }
    return false;
}
$result = in_array(timesShow, $time);

但它的返回错误如

movies:620 Uncaught TypeError: Cannot read property 'time' of undefined

5 个答案:

答案 0 :(得分:1)

使用 Array#Filter

return array.filter(x=>x.time==id).length > 0

答案 1 :(得分:1)

试试这个......

for(var i=0;i<array.length;i++) {
   if(array[i].time === id)
   {
       array[i].type='whatever you want to change';
   }
}

答案 2 :(得分:0)

var obj = [
 {time: "2:00pm",type:16},
 {time: "3:30pm",type:30},
 {time: "5:00pm",type:90}
];
obj.forEach(function(ob){
 if(ob.time == "3:30pm") ob.type = 50;
});
console.log(obj)

使用forEach循环遍历数组对象,然后使用时间值检查匹配是否更改同一对象的类型。

答案 3 :(得分:0)

您可以只使用没有其他索引的项目并返回该项目(如果找到)。

&#13;
&#13;
function getItem(array, id) {
    var i;
    for (i = 0; i < array.length; i++) {
        if (array[i].time === id) {
            return array[i];
        }
    }
}

var timesShow = [{ time: "2:00pm", type: 16 }, { time: "3:30pm", type: 30 }, { time: "5:00pm", type: 90 }];

console.log(getItem(timesShow, "3:30pm"));
console.log(getItem(timesShow, "2:30pm"));
&#13;
&#13;
&#13;

ES6与Array#find

&#13;
&#13;
function getItem(array, id) {
    return array.find(o => o.time === id);
}

var timesShow = [{ time: "2:00pm", type: 16 }, { time: "3:30pm", type: 30 }, { time: "5:00pm", type: 90 }];

console.log(getItem(timesShow, "3:30pm"));
console.log(getItem(timesShow, "2:30pm"));
&#13;
&#13;
&#13;

答案 4 :(得分:0)

试试这个:

    var obj = [
     {time: "2:00pm",type:16},
     {time: "3:30pm",type:30},
     {time: "5:00pm",type:90}
    ];
    var finalResult = obj.filter(function(d){
     if(d.time == "3:30pm"){d['type'] = 40}
     return d;
    });
console.log(finalResult)
相关问题