[英]How to change value of object which is inside an array using JavaScript or jQuery?
The code below comes from jQuery UI Autocomplete:下面的代码来自 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"
}
];
For example, I want to change the desc value of jquery-ui .例如,我想更改jquery-ui 的 desc 值。 How can I do that?
我怎样才能做到这一点?
Additionally, is there a faster way to get the data?另外,有没有更快的方法来获取数据? I mean give the object a name to fetch its data, just like the object inside an array?
我的意思是给对象一个名称以获取其数据,就像数组中的对象一样? So it would be something like
jquery-ui.jquery-ui.desc = ....
所以它会像
jquery-ui.jquery-ui.desc = ....
It is quite simple这很简单
findIndex
method.findIndex
方法查找对象的索引。yourArray[indexThatyouFind]
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])
You have to search in the array like:您必须在数组中搜索,例如:
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!
}
}
}
and use it like并像使用它一样
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
UPDATE:更新:
To get it faster:为了更快地获得它:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.) (根据 Frédéric 的评论,你不应该在对象键中使用连字符,或者你应该使用 "jquery-ui" 和 projects["jquery-ui"] 表示法。)
The best solution, thanks to ES6.最好的解决方案,感谢 ES6。
This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".这将返回一个新数组,其中包含值等于“jquery-ui”的对象的替换描述。
const newProjects = projects.map(p =>
p.value === 'jquery-ui'
? { ...p, desc: 'new description' }
: p
);
Using map is the best solution without using extra libraries.(using ES6)使用 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
);
ES6 way, without mutating original data. 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 sure to avoid incorrect replacement
// When specific item is not found
if (objIndex === -1) {
return;
}
// 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);
you can use .find so in your example您可以在示例中使用 .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'
given the following data, we want to replace berries in the summerFruits
list with watermelon .给定以下数据,我们想将
summerFruits
列表中的berries替换为watermelon 。
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
:第二种方法:使用
map
和spread
:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
summerFruitsCopy
list will now return an array with updated object. summerFruitsCopy
列表现在将返回一个包含更新对象的数组。
It's easily can be accomplished with underscore/lodash library:使用 underscore/lodash 库可以轻松完成:
_.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"}).value();
Docs:文件:
https://lodash.com/docs#find https://lodash.com/docs#find
https://lodash.com/docs#merge https://lodash.com/docs#merge
you need to know the index of the object you are changing.您需要知道要更改的对象的索引。 then its pretty simple
那么它很简单
projects[1].desc= "new string";
This is another answer involving find
.这是另一个涉及
find
的答案。 This relies on the fact that find
:这取决于
find
:
Here's the critical Javascript snippet:这是关键的 Javascript 片段:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
Here's an alternate version of the same Javascript:这是相同 Javascript 的替代版本:
projects.find( function (p) {
if (p.value === 'jquery-ui') {
p.desc = 'your value';
return true;
}
return false;
} );
Here's an even shorter (and somewhat more evil version):这是一个更短(也更邪恶的版本):
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
Here's a full working version:这是一个完整的工作版本:
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 ) );
I think this way is better我认为这种方式更好
const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";
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} // ]
// 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)];
try using forEach(item,index)
helper尝试使用
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 '
})
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)
What this code does is map over the object and then match the desired with if statement ,这段代码所做的是映射对象,然后将所需的与if 语句匹配,
if(user.id === 1)
once there is match somewhere use its index to swap一旦有匹配的地方使用它的索引来交换
users[index] = {id: 1, name: 'Baba Benny'};
the object in the array and then return the modified array数组中的对象,然后返回修改后的数组
Change value with conditions using for each loop使用每个循环的条件更改值
projects.forEach((p,index)=>{
if(index === 1){
p.value = "Updated jquery-ui"
}
})
You can use map function --您可以使用地图功能 -
const answers = this.state.answers.map(answer => {
if(answer.id === id) return { id: id, value: e.target.value }
return answer
})
this.setState({ answers: answers })
You can use for each, for loop for that您可以使用 for each, for 循环
const 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" } ]; for (let project of projects){ if(project.value === "jquery-ui"){ project.desc = "change value of desc of jquery-ui" } } console.log(projects)
Using map使用地图
const newProject = projects.map((project, index)=>{
if(project.value === "jquery-ui"){
project.desc = "change value of desc of jquery-ui"
}
});
console.log(newProject)
//Find index of specific object using findIndex method.
objIndex = projects.findIndex((obj => obj.value === "jquery-ui"));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
projects[objIndex].desc = "change value of desc of jquery-ui"
Here is a nice neat clear answer.这是一个很好的简洁清晰的答案。 I wasn't 100% sure this would work but it seems to be fine.
我不是 100% 确定这会起作用,但它似乎没问题。 Please let me know if a lib is required for this, but I don't think one is.
请让我知道这是否需要一个库,但我认为不需要。 Also if this doesn't work in x browser please let me know.
另外,如果这在 x 浏览器中不起作用,请告诉我。 I tried this in Chrome IE11 and Edge they all seemed to work fine.
我在 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>");
});
Output should be as follows输出应该如下
Ajay Smith阿杰·史密斯
Jack Black杰克布莱克
John Test3约翰测试3
Steve Test4史蒂夫测试4
Assuming you wanted to run a bit more complicated codes during the modification, you might reach for an if-else statement over the ternary operator approach假设您想在修改期间运行一些更复杂的代码,您可能会在三元运算符方法上使用 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);
We can also use Array's map function to modify object of an array using Javascript.我们还可以使用 Array 的 map 函数来使用 Javascript 修改数组的对象。
function changeDesc(value, desc){
projects.map((project) => project.value == value ? project.desc = desc : null)
}
changeDesc('jquery', 'new description')
The power of javascript destructuring 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));
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
);
Find the index first:首先找到索引:
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++;
}
}
Then:然后:
console.log(getIndex($scope.rides, "_id", id));
Then do what you want with this index, like:然后用这个索引做你想做的事,比如:
$scope[returnedindex].someKey = "someValue"; $scope[returnedindex].someKey = "someValue";
Note: please do not use for, since for will check all the array documents, use while with a stopper, so it will stop once it is found, thus faster code.注意:请不要使用 for,因为 for 会检查所有的数组文件,使用 while 有一个停止器,所以一旦找到它就会停止,这样代码会更快。
Here i am using angular js.在这里我使用角度 js。 In javascript you can use for loop to find.
在 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");
}
You can create your specific function like the below, then use that everywhere you need.您可以像下面这样创建您的特定功能,然后在您需要的任何地方使用它。
var each = (arr, func) =>
Array.from(
(function* (){
var i = 0;
for(var item of arr)
yield func(item, i++);
})()
);
Enjoy..享受..
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]
};
}
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map() 方法创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的函数的结果。
![]()
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 = projects.map((project, i) => { return { value: "Change to any value", } }); console.log(projects)<\/code><\/pre>
"
to update multiple items with the matches use:使用匹配更新多个项目:
_.chain(projects).map(item => {
item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
return item;
})
Try this code.试试这个代码。 it uses jQuery grep function
它使用 jQuery grep 函数
array = $.grep(array, function (a) {
if (a.Id == id) {
a.Value= newValue;
}
return a;
});
This is my response to the problem.这是我对这个问题的回应。 My underscore version was 1.7 hence I could not use
.findIndex
.我的下划线版本是 1.7,因此我无法使用
.findIndex
。
So I manually got the index of item and replaced it.所以我手动获取了项目的索引并替换了它。 Here is the code for the same.
这是相同的代码。
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" }
]
Below method will replace the student with id:4
with more attributes in the object下面的方法将用对象中的更多属性替换
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"});
} }
With underscore 1.8 it will be simplified as we have methods _.findIndexOf
.使用下划线 1.8 将简化,因为我们有方法
_.findIndexOf
。
Let you want to update value of array[2] = "data"
让你想更新
array[2] = "data"
的值
for(i=0;i<array.length;i++){
if(i == 2){
array[i] = "data";
}
}
let thismoth = moment(new Date()).format('MMMM');
months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.