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


当前回答

首先查找索引:

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

let users = [
    {id: 1, name: 'Benedict'},
    {id: 2, name: 'Myles'},
    {id: 3, name: 'Happy'},
]

 users.map((user, index) => {
 if(user.id === 1){
  users[index] = {id: 1, name: 'Baba Benny'};    
 }
 
 return user
})


console.log(users)

这段代码所做的是映射对象,然后匹配所需的 使用if语句,

if(user.id === 1) 

一旦有匹配的地方使用它的索引交换

 users[index] = {id: 1, name: 'Baba Benny'};

对象,然后返回修改后的数组

你可以使用map函数——

const answers = this.state.answers.map(answer => {
  if(answer.id === id) return { id: id, value: e.target.value }
  return answer
})

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

首先查找索引:

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带有一个停止器,因此一旦找到它就会停止,从而更快地编写代码。