下面的代码来自jQuery UI自动完成:

var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];

例如,我想更改jquery-ui的desc值。我该怎么做呢?

此外,是否有更快的方法来获取数据?我的意思是给对象一个名字来获取它的数据,就像数组中的对象一样?比如jquery-ui。jquery-ui。desc = ....


当前回答

let thismoth = moment(new Date()).format('MMMM');
months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });

其他回答

试试这段代码。它使用jQuery的grep函数

array = $.grep(array, function (a) {
    if (a.Id == id) {
        a.Value= newValue;
    }
    return a;
});

它可以很容易地用下划线/lodash库完成:

  _.chain(projects)
   .find({value:"jquery-ui"})
   .merge({desc: "new desc"}).value();

文档: https://lodash.com/docs#find https://lodash.com/docs#merge

这很简单

使用findIndex方法查找对象的索引。 将索引存储在变量中。 做一个简单的更新,像这样:

//Initailize array of objects. let myArray = [ {id: 0, name: "Jhon"}, {id: 1, name: "Sara"}, {id: 2, name: "Domnic"}, {id: 3, name: "Bravo"} ], //Find index of specific object using findIndex method. objIndex = myArray.findIndex((obj => obj.id == 1)); //Log object to Console. console.log("Before update: ", myArray[objIndex]) //Update object's name property. myArray[objIndex].name = "Laila" //Log object to console again. console.log("After update: ", myArray[objIndex])

这里我使用的是angular js。在javascript中,你可以使用for循环来查找。

    if($scope.bechval>0 &&$scope.bechval!=undefined)
    {

                angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
                $scope.model.benhmarkghamlest[key].bechval = $scope.bechval;

            });
    }
    else {
        alert("Please sepecify Bechmark value");
    }

你必须像这样在数组中搜索:

function changeDesc( value, desc ) {
   for (var i in projects) {
     if (projects[i].value == value) {
        projects[i].desc = desc;
        break; //Stop this loop, we found it!
     }
   }
}

然后像这样使用它

var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );

更新:

为了更快:

var projects = {
   jqueryUi : {
      value:  'lol1',
      desc:   'lol2'
   }
};

projects.jqueryUi.desc = 'new string';

(根据Frédéric的评论,你不应该在对象键中使用连字符,或者你应该使用“jquery-ui”和项目["jquery-ui"]符号。)