【问题标题】:How to change value of object which is inside an array using JavaScript or jQuery?如何使用 JavaScript 或 jQuery 更改数组内对象的值?
【发布时间】:2011-06-09 01:24:33
【问题描述】:

以下代码来自jQuery UI Autocomplete:

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 = ....

【问题讨论】:

  • 您必须将数组转换为 Javascript 对象才能使用语法 projects["jquery-ui"].desc。仅仅为了获得更好的语法而付出努力是否值得?
  • 我已经用您的最新问题更新了我的解决方案。您可以使用“projects.jquery-ui.desc”表示法。
  • ** ↑ aston 的意思是,如果对象结构按照他下面的回答进行了更改,您可以使用该表示法。 (与 OP 的现有示例结构。)
  • 对于新手,只需使用.find(),它是数组的一种方法,在这种情况下非常有用。请参阅abe kur's answer

标签: javascript jquery arrays


【解决方案1】:

您需要知道要更改的对象的索引。然后就很简单了

projects[1].desc= "new string";

【讨论】:

    【解决方案2】:

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

    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" 和 projects["jquery-ui"] 表示法。)

    【讨论】:

    • 有更快的方法来获取数据吗?我的意思是给对象一个名称来获取它的数据。就像数组中的对象一样。所以,我可以这样使用吗:jquery-ui.jquery-ui.desc = ....
    • 由于对象名称中的连字符 -,您的更新将不起作用。你必须分别写"jquery-ui": {}projects["jquery-ui"].desc
    • 谢谢,我不知道。
    • 看阿贝库尔的回答,没错,这个等都长了
    • 对于新手,只需使用.find(),它是数组的一种方法,在这种情况下非常有用。请参阅abe kur's answer
    【解决方案3】:

    您可以使用$.each() 遍历数组并找到您感兴趣的对象:

    $.each(projects, function() {
        if (this.value == "jquery-ui") {
            this.desc = "Your new description";
        }
    });
    

    【讨论】:

      【解决方案4】:

      使用 underscore/lodash 库可以轻松实现:

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

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

      【讨论】:

      • 如果 find 函数没有找到 'jquery-ui' 怎么办?
      • “LoDashExplicitArrayWrapper”类型上不存在属性“find”
      • 此类序列的结果必须用 _#value 展开。 lodash.com/docs/4.17.4#chain.value()
      【解决方案5】:

      使用匹配更新多个项目:

      _.chain(projects).map(item => {
            item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
            return item;
          })
      

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

          【解决方案7】:

          其实很简单

          • 使用findIndex方法查找对象的索引。
          • 将索引存储在变量中。
          • 像这样进行简单的更新:yourArray[indexThatyouFind]

          //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])

          【讨论】:

          • findIndex 方法上的双 () 有什么原因吗?
          • 它将改变 myArray。
          • 是的,但是如果您不想变异。 [...myArray.slice(0, objIndex), Object.assign({}, myArray[objIndex], myArray.slice(objIndex + 1))]
          • @UmairAhmed 上面的代码不应该是[...myArray.slice(0, objIndex), Object.assign({}, myArray[objIndex], ...myArray.slice(objIndex + 1))] 吗?我想你错过了第二个省略号。
          • 爱干净!
          【解决方案8】:

          这是我对这个问题的回应。我的下划线版本是 1.7,因此我无法使用 .findIndex

          所以我手动获取了项目的索引并替换了它。这是相同的代码。

           var students = [ 
          {id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" },
          {id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" },
          {id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" },
          {id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" }
                         ]
          

          下面的方法将用id:4替换student,对象中有更多属性

          function updateStudent(id) {
           var indexOfRequiredStudent = -1;
              _.each(students,function(student,index) {                    
                if(student.id === id) {                        
                     indexOfRequiredStudent = index; return;      
                }});
           students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"});           
          

          }

          下划线 1.8 将简化,因为我们有方法 _.findIndexOf

          【讨论】:

            【解决方案9】:

            您可以在示例中使用 .find

               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"
                        }
                    ];
            
            let project = projects.find((p) => {
                return p.value === 'jquery-ui';
            });
            
            project.desc = 'your value'
            

            【讨论】:

              【解决方案10】:

              我们也可以使用 Array 的 map 函数来使用 Javascript 修改数组的对象。

              function changeDesc(value, desc){
                 projects.map((project) => project.value == value ? project.desc = desc : null)
              }
              
              changeDesc('jquery', 'new description')
              

              【讨论】:

              • 这将返回 [null, object with the updated value, null]
              【解决方案11】:

              // using higher-order functions to avoiding mutation
              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"
                          }
                      ];
              
              // using higher-order functions to avoiding mutation
              index = projects.findIndex(x => x.value === 'jquery-ui');
              [... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)];

              【讨论】:

              • 这个... 之前的项目是必要的?
              • @lazzy_ms ... 被称为扩展运算符。谷歌它:)
              【解决方案12】:

              先找到索引:

              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));
              

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

              $scope[returnedindex].someKey = "someValue";

              注意:请不要使用for,因为for会检查所有的数组文档,使用while带一个stopper,这样一找到就停止,这样代码会更快。

              【讨论】:

                【解决方案13】:

                ES6 方式,没有变异原始数据。

                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"
                }];
                
                //find the index of object from array that you want to update
                const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');
                
                // make new object of updated object.   
                const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};
                
                // make final new array of objects by combining updated object.
                const updatedProjects = [
                  ...projects.slice(0, objIndex),
                  updatedObj,
                  ...projects.slice(objIndex + 1),
                ];
                
                console.log("original data=", projects);
                console.log("updated data=", updatedProjects);
                

                【讨论】:

                  【解决方案14】:

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

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

                  const newProjects = projects.map(p =>
                    p.value === 'jquery-ui'
                      ? { ...p, desc: 'new description' }
                      : p
                  );
                  

                  【讨论】:

                  • @FrederikoCesar 并非在所有情况下,迭代每个对象的成本都高于切片数组并使用扩展运算符注入新对象
                  • 如果您想即时更改值怎么办?不创建另一个变量?最好的方法是索引方法: const targetIndex = summerFruits.findIndex(f=>f.id===3);
                  • 这很棒而且很简短。你能写出如何同时更新两个值吗?速记符号对我来说肯定很难理解。 ? : if else what's "..."
                  • @SgtPepperAut 也许这样:proj.map(p =&gt; ['jquery-ui', 'other-value'].includes(p.value) ? { ...p, desc: 'new-description' } : p )
                  • 对于新手,只需使用.find(),它是数组的一种方法,在这种情况下非常有用。请参阅abe kur's answer
                  【解决方案15】:

                  这里我使用的是 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");
                      }
                  

                  【讨论】:

                    【解决方案16】:

                    我觉得这样比较好

                    const index = projects.findIndex(project => project.value==='jquery-ui');
                    projects[index].desc = "updated desc";
                    

                    【讨论】:

                    • 在您的findIndex 中,您正在分配一个值而不是比较
                    【解决方案17】:

                    你可以使用地图功能 --

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

                    【讨论】:

                      【解决方案18】:

                      使用 map 是不使用额外库的最佳解决方案。(使用 ES6)

                      const state = [
                      {
                          userId: 1,
                          id: 100,
                          title: "delectus aut autem",
                          completed: false
                      },
                      {
                          userId: 1,
                          id: 101,
                          title: "quis ut nam facilis et officia qui",
                          completed: false
                      },
                      {
                          userId: 1,
                          id: 102,
                          title: "fugiat veniam minus",
                          completed: false
                      },
                      {
                          userId: 1,
                          id: 103,
                          title: "et porro tempora",
                          completed: true
                      }]
                      
                      const newState = state.map(obj =>
                          obj.id === "101" ? { ...obj, completed: true } : obj
                      );
                      

                      【讨论】:

                      【解决方案19】:

                      鉴于以下数据,我们想将summerFruits列表中的berries替换为西瓜

                      const summerFruits = [
                      {id:1,name:'apple'}, 
                      {id:2, name:'orange'}, 
                      {id:3, name: 'berries'}];
                      
                      const fruit = {id:3, name: 'watermelon'};
                      

                      有两种方法可以做到这一点。

                      第一种方法:

                      //create a copy of summer fruits.
                      const summerFruitsCopy = [...summerFruits];
                      
                      //find index of item to be replaced
                      const targetIndex = summerFruits.findIndex(f=>f.id===3); 
                      
                      //replace the object with a new one.
                      summerFruitsCopy[targetIndex] = fruit;
                      

                      第二种方法:使用mapspread

                      const summerFruitsCopy = summerFruits.map(fruitItem => 
                      fruitItem .id === fruit.id ? 
                          {...summerFruits, ...fruit} : fruitItem );
                      

                      summerFruitsCopy list 现在将返回一个包含更新对象的数组。

                      【讨论】:

                      • 第一种方法最好。无需移动到另一个 var 然后返回。在飞行方法。我对你的解决方案投了赞成票。
                      【解决方案20】:

                      让你想更新array[2] = "data"的值

                          for(i=0;i<array.length;i++){
                            if(i == 2){
                               array[i] = "data";
                              }
                          }
                      

                      【讨论】:

                      • 这是答案还是问题?
                      • 您以最复杂的方式成功更新了该数组中的第二项。
                      【解决方案21】:
                      let thismoth = moment(new Date()).format('MMMM');
                      months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });
                      

                      【讨论】:

                      • 请对您的回答进行描述。
                      【解决方案22】:

                      这是另一个涉及find 的答案。 这取决于find:

                      • 遍历数组中的每个对象,直到找到匹配项
                      • 每个对象都提供给您并且可以修改

                      这是关键的 Javascript sn-p:

                      projects.find( function (p) {
                          if (p.value !== 'jquery-ui') return false;
                          p.desc = 'your value';
                          return true;
                      } );
                      

                      这是相同 Javascript 的替代版本:

                      projects.find( function (p) {
                          if (p.value === 'jquery-ui') {
                              p.desc = 'your value';
                              return true;
                          }
                          return false;
                      } );
                      

                      这里有一个更短(也更邪恶的版本):

                      projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
                      

                      这是一个完整的工作版本:

                        let 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"
                                  }
                              ];
                      
                      projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
                      
                      console.log( JSON.stringify( projects, undefined, 2 ) );

                      【讨论】:

                      • 哇,这是你刚刚在那里施展的魔法!
                      【解决方案23】:

                      尝试使用forEach(item,index) 助手

                      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"
                          }
                      ];
                      
                      let search_to_change = 'jquery'
                      
                      projects.forEach((item,index)=>{
                         if(item.value == search_to_change )
                            projects[index].desc = 'your description ' 
                      })
                      
                      

                      【讨论】:

                        【解决方案24】:

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

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

                        享受..

                        【讨论】:

                        • 欢迎来到社区,如果你解释一下发生了什么以及它是如何工作的,那么显然每个人都可以Enjoy..
                        【解决方案25】:

                        这是一个简洁明了的答案。我不是 100% 确定这会起作用,但它似乎没问题。请让我知道这是否需要一个库,但我认为不需要。另外,如果这在 x 浏览器中不起作用,请告诉我。我在 Chrome IE11 和 Edge 中尝试过,它们似乎都可以正常工作。

                            var Students = [
                                { ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
                                { ID: 2, FName: "Jack", LName: "Test2", Age: 21},
                                { ID: 3, FName: "John", LName: "Test3", age: 22},
                                { ID: 4, FName: "Steve", LName: "Test4", Age: 22}
                            ]
                        
                            Students.forEach(function (Student) {
                                if (Student.LName == 'Test1') {
                                    Student.LName = 'Smith'
                                }
                                if (Student.LName == 'Test2') {
                                    Student.LName = 'Black'
                                }
                            });
                        
                            Students.forEach(function (Student) {
                                document.write(Student.FName + " " + Student.LName + "<BR>");
                            });
                        

                        输出应该如下

                        阿杰·史密斯

                        杰克·布莱克

                        约翰测试3

                        史蒂夫测试4

                        【讨论】:

                          【解决方案26】:
                          upsert(array, item) { 
                                  const i = array.findIndex(_item => _item.id === item.id);
                                  if (i > -1) {
                                      let result = array.filter(obj => obj.id !== item.id);
                                      return [...result, item]
                                  }
                                  else {
                                      return [...array, item]
                                  };
                              }
                          

                          【讨论】:

                            【解决方案27】:

                            javascript 解构的力量

                            const projects = [
                              {
                                value: 'jquery',
                                label: 'jQuery',
                                desc: 'the write less, do more, JavaScript library',
                                icon: 'jquery_32x32.png',
                                anotherObj: {
                                  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',
                              },
                            ];
                            
                            function createNewDate(date) {
                              const newDate = [];
                              date.map((obj, index) => {
                                if (index === 0) {
                                  newDate.push({
                                    ...obj,
                                    value: 'Jquery??',
                                    label: 'Jquery is not that good',
                                    anotherObj: {
                                      ...obj.anotherObj,
                                      value: 'Javascript',
                                      label: 'Javascript',
                                      desc: 'Write more!!! do more!! with JavaScript',
                                      icon: 'javascript_4kx4k.4kimage',
                                    },
                                  });
                                } else {
                                  newDate.push({
                                    ...obj,
                                  });
                                }
                              });
                            
                              return newDate;
                            }
                            
                            console.log(createNewDate(projects));

                            【讨论】:

                              【解决方案28】:

                              假设您想在修改期间运行一些更复杂的代码,您可能会使用 if-else 语句而不是三元运算符方法

                              // original 'projects' array;
                              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"
                                  }
                              ];
                              
                              // modify original 'projects' array, and save modified array into 'projects' variable
                              projects = projects.map(project => {
                              // When there's an object where key 'value' has value 'jquery-ui'
                                  if (project.value == 'jquery-ui') {
                              
                              // do stuff and set a new value for where object's key is 'value'
                                      project.value = 'updated value';
                              
                              // do more stuff and also set a new value for where the object's key is 'label', etc.
                                      project.label = 'updated label';
                              
                              // now return modified object
                                      return project;
                                  } else {
                              // just return object as is
                                      return project;
                                  }
                              });
                              
                              // log modified 'projects' array
                              console.log(projects);
                              

                              【讨论】:

                                【解决方案29】:

                                const users = [
                                  { name: "Alex", age: 25 },
                                  { name: "John", age: 32 },
                                ];
                                
                                const newUsers = users.map((user) => ({
                                  ...user,
                                  age: user.age + 5, // just for example
                                }));
                                
                                // newUsers = [
                                // {name:"Alex" , age:30},
                                // {name:"John , age:37}
                                // ]

                                【讨论】:

                                • IMO 最智能的解决方案!顺便说一句,技术上最好的。
                                【解决方案30】:
                                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'};
                                

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

                                【讨论】:

                                • 不要写代码,请解释那里发生了什么
                                • 已经有 29 个答案了。接受的答案有 183 个赞成票。为什么我们需要另一个答案?之前的 29 个答案尚未涵盖的此答案产品是什么?
                                • @JeremyCaney 这是因为有很多方法可以给猫剥皮,同时通过为读者提供代码流的真实性,他们可以选择一种或混合搭配方法
                                • @mwangaben 返回值将是用户,而不是用户
                                • @sayinmehmet47 感谢您指出我已经修复了
                                猜你喜欢
                                • 2023-03-27
                                • 1970-01-01
                                • 2021-10-29
                                • 1970-01-01
                                • 2010-09-18
                                • 2020-07-27
                                • 2020-09-24
                                • 2021-09-29
                                • 2013-12-29
                                相关资源
                                最近更新 更多