如何使用JavaScript或jQuery更改数组内的对象的值?

时间:2011-01-14 09:59:56

标签: javascript jquery arrays

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

29 个答案:

答案 0 :(得分:132)

很简单

  • 使用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])

答案 1 :(得分:80)

您必须在数组中搜索:

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”和project [“jquery-ui”]表示法。)

答案 2 :(得分:33)

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

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

答案 3 :(得分:23)

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

答案 4 :(得分:17)

使用下划线/ lodash库可以轻松完成:

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

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

答案 5 :(得分:15)

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

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

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

答案 6 :(得分:11)

您需要知道要更改的对象的索引。那很简单

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

答案 7 :(得分:10)

使用地图是不使用额外库的最佳解决方案。(使用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
);

答案 8 :(得分:7)

这是另一个涉及find的答案。 这取决于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;
} );

这是同一Javascript的替代版本:

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

这是一个更短的版本(有些邪恶的版本):

  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"
            }
        ];

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

console.log( JSON.stringify( projects, undefined, 2 ) );

这是完整的工作版本:

public static void main(String[] args){
        Another i
        System.out.println(a.i);
    }

答案 9 :(得分:6)

你可以在你的例子中使用.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 :(得分:3)

&#13;
&#13;
// 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)];
&#13;
&#13;
&#13;

答案 11 :(得分:2)

尝试使用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 ' 
})

答案 12 :(得分:1)

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

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

享受..

答案 13 :(得分:1)

我认为这种方式更好

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

答案 14 :(得分:0)

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]
        };
    }

答案 15 :(得分:0)

这是一个很好的简洁答案。我不是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>");
    });

输出应如下

阿杰·史密斯

杰克·布莱克

John Test3

Steve Test4

答案 16 :(得分:0)

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

答案 17 :(得分:0)

假设您想在修改过程中运行更复杂的代码,您可能会通过三元运算符方法使用 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);

答案 18 :(得分:0)

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

答案 19 :(得分:0)

鉴于以下数据,我们希望将夏季水果列表中的浆果替换为西瓜。

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

const fruit = {id:3, name: 'watermelon'};

Two ways you can do this.

First approach:

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

Second approach: using map, and spread 
const summerFruitsCopy = summerFruits.map(fruitItem => 
fruitItem .id === fruit.id ? 
    {...summerFruits, ...fruit} : fruitItem );

summerFruitsCopy列表现在将返回带有更新对象的数组。

答案 20 :(得分:0)

您可以使用地图功能-

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

this.setState({ answers: answers })

答案 21 :(得分:0)

在这里,我正在使用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");
    }

答案 22 :(得分: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));

然后使用此索引执行您想要的操作,例如:

$ scope [returnedindex] .someKey =&#34; someValue&#34;;

注意:请不要使用,因为for会检查所有的数组文件,同时使用带塞子,所以一旦找到就会停止,因此代码更快。

答案 23 :(得分:0)

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

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

changeDesc('jquery', 'new description')

答案 24 :(得分:0)

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

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

答案 25 :(得分:-1)

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

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

答案 26 :(得分:-1)

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

答案 27 :(得分:-1)

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

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

 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的学生替换为对象中的更多属性

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

答案 28 :(得分:-1)

使用匹配项更新多个项目:

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