繁体   English   中英

如何更改json数组中json对象中放置在数组中的值?

[英]How to change a value placed inside a array in a json object in json array?

我正在使用 javascript 来执行此操作。

我想将[0,0,1]更改为[3,0,1] ,其中id = 'a'

[
 {'id' : 'a', arr : [0,0,1]},
 {'id' : 'b', arr : [1,0,1]},
 {'id' : 'c', arr : [1,4,1]}
]

谢谢。

像这样尝试

let value =[
    {'id' : 'a', arr : [0,0,1]},
    {'id' : 'b', arr : [1,0,1]},
    {'id' : 'c', arr : [1,4,1]}
   ]
   value.forEach(val=>{
   if(val.id=='a'){
    val.arr=[3,0,1] 
   }
})
    You can have few different approach to achieve this
    1. using Map
        
  let tmp = [
    {'id' : 'a', arr : [0,0,1]},
    {'id' : 'b', arr : [1,0,1]},
    {'id' : 'c', arr : [1,4,1]}
   ]
   var updated_array;
   updated_array = tmp.map(function(element){
       if(element.id == 'a'){
         return {
          id: element.id,
          arr : [3,0,1]

          }   
       } else {
         return element
        }
   })
    
    2. Using Filter

   updated_array = tmp.filter(function(element){
    if(element.id == 'a'){
      return {
       id: element.id,
       arr : [3,0,1]

       }   
    } else {
      return element
     }
})

    3. Using ForEach


tmp.forEach(function(element){
          if(element.id == 'a'){
            element.arr = [3,0,1]
          }
        }) 


    4. You can also use traditional while or for loop to achieve this

您可以使用数组的 map() 并更新值。 检查下面的代码。

 let tmp = [ {'id' : 'a', arr : [0,0,1]}, {'id' : 'b', arr : [1,0,1]}, {'id' : 'c', arr : [1,4,1]} ] tmp.map(item =>{ if (item.id === 'a'){ item.arr=[3,0,1]; } }) console.log(tmp);

暂无
暂无

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

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