繁体   English   中英

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

[英]Update existing JS associative array with new value

我想在下面的数组中搜索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

使用Array#Filter

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

尝试这个...

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

 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遍历数组对象,然后检查时间值是否匹配相同对象的更改类型。

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

 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")); 

具有Array#find ES6

 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")); 

尝试这个:

    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)

暂无
暂无

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

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