簡體   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