简体   繁体   中英

Update existing JS associative array with new value

I want to search 3.30pm in below array and update the type value of the array index in JS

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

Any one please suggest the correct way to fix it.

I tried this..

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

But its returning error like

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

使用Array#Filter

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

Try this...

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) 

Loop through array object using forEach , then check with the time value if matches change type of same object.

You could use just the item without another index and return the item, if found.

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

ES6 with Array#find

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

Try this:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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