下面的代码来自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 = ....


当前回答

您可以像下面这样创建特定的函数,然后在需要的任何地方使用它。

var each    = (arr, func) => 
                Array.from(
                    (function* (){
                        var i = 0;
                        for(var item of arr)
                            yield func(item, i++);
                    })()
                );

享受. .

其他回答

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

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"]符号。)

首先查找索引:

function getIndex(array, key, value) {
        var found = false;
        var i = 0;
        while (i<array.length && !found) {
          if (array[i][key]==value) {
            found = true;
            return i;
          }
          i++;
        }
      }

然后:

console.log(getIndex($scope.rides, "_id", id));

然后对这个索引做你想做的事情,比如:

美元(returnedindex)范围。someKey = "someValue";

注意:请不要使用for,因为for将检查所有的数组文档,使用while带有一个停止器,因此一旦找到它就会停止,从而更快地编写代码。

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

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

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

最好的解决方案,感谢ES6。

这将返回一个新的数组,其中替换了对象的描述,其中包含等于"jquery-ui"的值。

const newProjects = projects.map(p =>
  p.value === 'jquery-ui'
    ? { ...p, desc: 'new description' }
    : p
);
let thismoth = moment(new Date()).format('MMMM');
months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });