如何改变对象的值,这是一个数组使用JavaScript或jQuery?

下面的代码来自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的值。我该怎么做呢?

此外,是否有更快的方法来获取数据?我的意思是给对象一个名字来获取它的数据,就像数组中的对象一样?所以它会是类似jquery-ui.jquery-ui.desc = ....的东西

1116110 次浏览

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

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 ()遍历数组并定位你感兴趣的对象:

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

它可以很容易地用下划线/lodash库完成:

  _.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"}).value();
< p >文档:< br > https://lodash.com/docs#find < br > https://lodash.com/docs#merge < / p >

要更新多个匹配项,请使用:

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

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

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

这很简单

  • 使用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.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

你可以在你的例子中使用。find so

   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'

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

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


changeDesc('jquery', 'new description')

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

首先查找索引:

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

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

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

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

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

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

我认为这样比较好

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

你可以使用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 })

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

给定以下数据,我们想用西瓜替换summerFruits列表中的浆果

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现在将返回一个包含更新对象的数组。

让你想要更新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; });
这是另一个涉及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;
} );

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

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

尝试使用forEach(item,index) helper

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++);
})()
);

享受. .

这里有一个简洁明了的答案。我不是百分百确定这能行,但看起来还行。请让我知道,如果一个库是必需的,但我不认为是。另外,如果这在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>");
});

输出应该如下所示

Ajay史密斯

杰克·布莱克

约翰Test3

史蒂夫Test4

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

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

假设您希望在修改期间运行更复杂的代码,您可能会使用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);

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

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语句 < / p >
if(user.id === 1)

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

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

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

用每个循环使用的条件更改值

projects.forEach((p,index)=>{
if(index === 1){
p.value = "Updated jquery-ui"
}
})
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
);

我们可以这样改变

const oldArray = [{username: gopal, age: 20}, {username: gopi, age: 21}]
const obj = {username: gopal, age: 25}
const result = oldArray.map(d => d.username === 'gopi' ? d.age = obj.age : d)