1

我刚刚开始这样做,所以我对如何使用以下内容感到困惑。

// so I believe this really isn't an object just a string representation, but for example please excuse the name
var dataObj = "{'id': 1, 
                'data': { 'color': 'red', 
                          'shape' : 'triangle', 
                          'height' : 100, 
                          'width' : 45, 
                           },
                'id': 2, 
                'data': { 'color': 'blue', 
                          'shape' : 'square', 
                          'height' : 75, 
                          'width' : 67, 
                          },
                'id': 3, 
                'data': { 'color': 'orange', 
                          'shape' : 'circle', 
                          'height' : 89, 
                          'width' :24, 
                          }
                }";

所以我遇到的问题是如何通过 id 更新数据值的特定子集(比如 SQL UPDATE WHERE 之类的东西)?javascript 或 jquery 对我来说真的无关紧要,只是不知道任何一种方法。

dataObjUpdate(2);    
function dataObjUpdate (passedID) {

    //access the data by the passedID match and update the color to black
}

感谢帮助家伙....

4

1 回答 1

2

如果我们忽略我留下的评论并假设您有一个 JavaScript 对象。我看到以下问题:

  • 您的 ID 在您的嵌套对象之外。
  • 您正在使用一个对象,但您想要一个“列表”,您可以为此使用一个数组。

以下是我自己构建对象的方式:

var data = [{ 
        color : 'red', 
        shape : 'triangle', 
        height : 100, 
        width : 45, 
        id:1
    },
    { 
        color: 'blue', 
        shape : 'square', 
        height : 75, 
        width : 67, 
        id: 2
    },
    {
        color: 'orange', 
        shape : 'circle', 
        height : 89, 
        width :24,
        id :3 
    }];

现在,我可以像您期望的那样查询它filter

var id3 = data.filter(function(elem){
             return elem.id === 3;
          })[0];
   id3;//the third object, with id 3

ES6 有一个方法称为find,它会保存[0]在最后(这意味着第一个元素)

var id3 = data.find(function(elem){
             return elem.id === 3;
          });
   id3;//the third object, with id 3

或者,您可以使用简单的 for 循环

var id3 = (function find(arr){
              for(var i=0;i<arr.length;i++){
                  if(arr[i].id === 3){
                      return arr[i];
                  }
              }
          })(data);
id3;
于 2013-07-05T12:46:14.257 回答