如何使用JavaScript或jQuery更改数组中对象的值?
以下代码来自jQuery UI自动完成:如何使用JavaScript或jQuery更改数组中对象的值?,javascript,jquery,arrays,Javascript,Jquery,Arrays,以下代码来自jQuery UI自动完成: var项目=[ { 值:“jquery”, 标签:“jQuery”, desc:“写得少,做得多,JavaScript库”, 图标:“jquery_32x32.png” }, { 值:“jquery ui”, 标签:“jQueryUI”, desc:“jQuery的官方用户界面库”, 图标:“jqueryui_32x32.png” }, { 值:“sizzlejs”, 标签:“Sizzle JS”, desc:“一个纯JavaScript CSS选择器引
var项目=[
{
值:“jquery”,
标签:“jQuery”,
desc:“写得少,做得多,JavaScript库”,
图标:“jquery_32x32.png”
},
{
值:“jquery ui”,
标签:“jQueryUI”,
desc:“jQuery的官方用户界面库”,
图标:“jqueryui_32x32.png”
},
{
值:“sizzlejs”,
标签:“Sizzle JS”,
desc:“一个纯JavaScript CSS选择器引擎”,
图标:“sizzlejs_32x32.png”
}
];
例如,我想更改jquery ui的desc值。我该怎么做
此外,是否有更快的方法获取数据?我的意思是给对象一个名称来获取它的数据,就像数组中的对象一样?因此,它类似于
jquery-ui.jquery-ui.desc=..
您需要知道正在更改的对象的索引。那就很简单了
projects[1].desc= "new string";
您必须在数组中搜索,如下所示:
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”]符号。)你可以使用它来迭代数组并找到你感兴趣的对象:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});
使用下划线/lodash库可以轻松完成:
_.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"});
文档:要使用匹配项更新多个项目,请使用:
_.chain(projects).map(item => {
item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
return item;
})
试试这个代码。它使用jquerygrep函数
array = $.grep(array, function (a) {
if (a.Id == id) {
a.Value= newValue;
}
return a;
});
这很简单
- 使用
方法查找对象的索引findIndex
- 将索引存储在变量中
- 执行如下简单更新:
yourArray[IndexHatYouFind]
//初始化对象数组。
设myArray=[
{id:0,名称:“Jhon”},
{id:1,名字:“Sara”},
{id:2,名称:“域”},
{id:3,名字:“好极了”}
],
//使用findIndex方法查找特定对象的索引。
objIndex=myArray.findIndex((obj=>obj.id==1));
//将对象记录到控制台。
log(“更新前:”,myArray[objIndex])
//更新对象的名称属性。
myArray[objIndex].name=“Laila”
//再次将对象记录到控制台。
log(“更新后:,myArray[objIndex])
这是我对问题的回应。我的下划线版本是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
可以使用。在您的示例中可以找到
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'
我们还可以使用数组的map函数使用Javascript修改数组的对象
function changeDesc(value, desc){
projects.map((project) => project.value == value ? project.desc = desc : null)
}
changeDesc('jquery', 'new description')
//使用高阶函数避免变异
var项目=[
{
值:“jquery”,
标签:“jQuery”,
desc:“写得少,做得多,JavaScript库”,
图标:“jquery_32x32.png”
},
{
值:“jquery ui”,
标签:“jQueryUI”,
desc:“jQuery的官方用户界面库”,
图标:“jqueryui_32x32.png”
},
{
值:“sizzlejs”,
标签:“Sizzle JS”,
desc:“一个纯JavaScript CSS选择器引擎”,
图标:“sizzlejs_32x32.png”
}
];
//利用高阶函数避免变异
index=projects.findIndex(x=>x.value=='jqueryui');
[…projects.slice(0,index),{'x':'xxxx'},…projects.slice(index+1,projects.length)]代码>首先查找索引:
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++;
}
}
然后使用此索引执行所需操作,如:
$scope[returnedindex].someKey=“someValue”
注意:请不要使用for,因为for将检查所有数组文档,请使用while和stopper,因此一旦找到它,它将停止,从而加快代码速度。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);
由于ES6,这是最好的解决方案
这将返回一个新数组,其中包含一个值等于“jquery ui”的对象的替换描述
这里我使用的是AngularJS。在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");
}
我觉得这样比较好
const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";
您可以使用映射函数--
使用map是不使用额外库的最佳解决方案。(使用ES6)
根据以下数据,我们想用西瓜取代summerFruits
列表中的浆果
有两种方法可以做到这一点
第一种方法:
//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;
第二种方法:使用map
,和spread
:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
列表现在将返回一个包含更新对象的数组。允许您更新数组[2]=“数据”
for(i=0;i这是另一个涉及find
的答案。
这取决于以下事实:find
:
- 迭代数组中的每个对象,直到找到匹配项
- 每个对象都提供给您并且可以修改
下面是关键的Javascript代码片段:
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;
} );
这里有一个更简短的版本(更邪恶的版本):
以下是完整的工作版本:
var项目=[
{
值:“jquery”,
标签:“jQuery”,
desc:“写得少,做得多,JavaScript库”,
图标:“jquery_32x32.png”
},
{
值:“jquery ui”,
标签:“jQueryUI”,
desc:“jQuery的官方用户界面库”,
图标:“jqueryui_32x32.png”
},
{
值:“sizzlejs”,
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;
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
let thismoth = moment(new Date()).format('MMMM');
months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
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 ) );
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 '
})
var each = (arr, func) =>
Array.from(
(function* (){
var i = 0;
for(var item of arr)
yield func(item, i++);
})()
);
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>");
});
// 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);