qin*_*ang 153 javascript arrays jquery
下面的代码来自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"
}
];
Run Code Online (Sandbox Code Playgroud)
例如,我想更改jquery-ui的desc值.我怎样才能做到这一点?
此外,有更快的方式来获取数据吗?我的意思是给对象一个名称来获取它的数据,就像数组中的对象一样?所以它会是这样的jquery-ui.jquery-ui.desc = ....
Uma*_*med 176
这很简单
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])Run Code Online (Sandbox Code Playgroud)
Ast*_*ton 107
您必须在数组中搜索:
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!
}
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
Run Code Online (Sandbox Code Playgroud)
更新:
为了加快速度:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
Run Code Online (Sandbox Code Playgroud)
(根据Frédéric的评论,你不应该在对象键中使用连字符,或者你应该使用"jquery-ui"和项目["jquery-ui"]表示法.)
小智 68
使用 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
);
Run Code Online (Sandbox Code Playgroud)
Fré*_*idi 34
您可以使用$ .each()迭代数组并找到您感兴趣的对象:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});
Run Code Online (Sandbox Code Playgroud)
Bim*_*Grg 34
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);
Run Code Online (Sandbox Code Playgroud)
kin*_*aro 25
最好的解决方案,感谢ES6.
这将返回一个新数组,其中包含对象的替换描述,该对象包含等于"jquery-ui"的值.
const newProjects = projects.map(p =>
p.value === 'jquery-ui'
? { ...p, desc: 'new description' }
: p
);
Run Code Online (Sandbox Code Playgroud)
小智 19
给出下面的数据,我们要替换浆果在summerFruits与列表西瓜。
const summerFruits = [
{id:1,name:'apple'},
{id:2, name:'orange'},
{id:3, name: 'berries'}];
const fruit = {id:3, name: 'watermelon'};
Run Code Online (Sandbox Code Playgroud)
有两种方法可以做到这一点。
第一种方法:
//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;
Run Code Online (Sandbox Code Playgroud)
第二种方法:使用map, 和spread:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
Run Code Online (Sandbox Code Playgroud)
summerFruitsCopy list 现在将返回一个包含更新对象的数组。
小智 18
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}
// ]Run Code Online (Sandbox Code Playgroud)
小智 17
使用下划线/ lodash库可以轻松完成:
_.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"});
Run Code Online (Sandbox Code Playgroud)
文档:
https ://lodash.com/docs#find
https://lodash.com/docs#merge
小智 16
你可以在你的例子中使用.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'
Run Code Online (Sandbox Code Playgroud)
ela*_*ash 11
您需要知道要更改的对象的索引.那很简单
projects[1].desc= "new string";
Run Code Online (Sandbox Code Playgroud)
tsa*_*rek 11
我认为这种方式更好
const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";
Run Code Online (Sandbox Code Playgroud)
这是另一个涉及find. 这取决于以下事实find:
这是关键的 Javascript 代码段:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
Run Code Online (Sandbox Code Playgroud)
这是同一 Javascript 的替代版本:
projects.find( function (p) {
if (p.value === 'jquery-ui') {
p.desc = 'your value';
return true;
}
return false;
} );
Run Code Online (Sandbox Code Playgroud)
这是一个更短的(也更邪恶的版本):
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
Run Code Online (Sandbox Code Playgroud)
这是一个完整的工作版本:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
此代码的作用是映射对象,然后将所需的内容与if 语句进行匹配,
if(user.id === 1)
Run Code Online (Sandbox Code Playgroud)
一旦某个地方有匹配,就使用它的索引来交换
users[index] = {id: 1, name: 'Baba Benny'};
Run Code Online (Sandbox Code Playgroud)
数组中的对象,然后返回修改后的数组
使用 for 每个循环根据条件更改值
projects.forEach((p,index)=>{
if(index === 1){
p.value = "Updated jquery-ui"
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
408387 次 |
| 最近记录: |