2015-11-02 71 views
0

我需要尋找一個元素在JSON對象像這樣添加一些數據:搜索元素在JSON對象更新/在這個對象

var new_a = 'new'; 
var json = { cells: 
    [ { type: 'model', 
     id: '5aef826a1809', 
     attrs: { 
       text: 'first', 
       a: 'changethis' 
      } 
     }, 
     { type: 'model', 
     id: '2c11b8bd8112', 
     attrs: { 
       text: 'second' 
      } 
     } 
    ] 
} 
  1. 現在我想找到對象id = 5aef826a1809,因爲我想將a的值更改爲new_a或插入a -element(如果它不存在)。

  2. 如果id = 2c11b8bd8112應該添加一個新的a-元素new_a

我試圖用

var res = _.find(json.cells, { id: '5aef826a1809' }); // doesn't work 
res.attrs.a = new_a; // this would update or add new field, right? 

但這不起作用

+0

你想改變'一個''到的new_a'了''或名稱的價值? –

+0

我想改變這個值。 – user3142695

回答

0

嘗試像這樣

var new_a = 'new'; 
var json = { 
    cells: [{ 
     type: 'model', 
     id: '5aef826a1809', 
     attrs: { 
      text: 'first', 
      a: 'changethis' 
     } 
    }, { 
     type: 'model', 
     id: '2c11b8bd8112', 
     attrs: { 
      text: 'second' 
     } 
    }] 
}; 
var obj = json.cells.find(function (x) { 
    return x.id == '5aef826a1809' 
}); 
if (obj) { // return value if found else return undefined if not found 
    obj.attrs.a = new_a; 
    console.log(json); 
} 

JSFIDDLE

0

使用這個簡單的for循環應該工作,如果這就是你要找的內容:

for(var i = 0; i<json.cells.length; i++){ 
    if(json.cells[i].id == "5aef826a1809" || json.cells[i].id == "2c11b8bd8112"){ 
      json.cells[i].attrs.a = "new_a"; 
    } 
} 

希望它幫助。

0

您可以使用Array.prototype.some進行搜索,更改和進行短路,以防止進行更多的迭代。

var new_a = 'new', 
 
    json = { 
 
     cells: [{ 
 
      type: 'model', 
 
      id: '5aef826a1809', 
 
      attrs: { 
 
       text: 'first', 
 
       a: 'changethis' 
 
      } 
 
     }, { 
 
      type: 'model', 
 
      id: '2c11b8bd8112', 
 
      attrs: { 
 
       text: 'second' 
 
      } 
 
     }] 
 
    }; 
 

 
function change(id) { 
 
    json.cells.some(function (a) { 
 
     var i = id.indexOf(a.id); 
 
     if (~i) { 
 
      a.attrs = a.attrs || {}; 
 
      a.attrs.a = new_a; 
 
      id.splice(i, 1); 
 
      if (!id.length) { 
 
       return true; 
 
      } 
 
     } 
 
    }); 
 
} 
 

 
change(['5aef826a1809', '2c11b8bd8112']); 
 
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');