![](/img/trans.png)
[英]Find object having maximum value for the `id` property in an array of objects
[英]In an array of objects, how to update (not just find) the object having property X equal to Y?
我的對象數組包含不同類型的對象,這意味着它們可以具有非常不同的屬性。 然而,它們都共享一個id
屬性。
當我的應用程序的用戶想要更新這些對象之一時,我需要根據id
在數組中找到該對象並更新其所有屬性,可能使用Object.assign()
。
我知道如何根據id
查找和返回我想要的對象,但也不知道如何更新它。 任何的想法?
let myArray = [
{
id: 1,
name: 'john',
age: '22',
position: 'developer'
},
{
id: 2,
name: 'james',
age: '31',
position: 'designer'
},
{
id: 1,
name: 'david',
age: '45',
position: 'teacher'
}
]
let updateForJames = {
age: '38',
position: 'project manager'
}
let JamesId = 2
Object.assign(myArray, {
// ...
})
如果您對就地更改數組感到滿意,則可以使用.find()
查找具有給定 id 的對象,然后使用Object.assing()
更新該對象,如下所示:
const myArray = [{ id: 1, name: 'john', age: '22', position: 'developer' }, { id: 2, name: 'james', age: '31', position: 'designer' }, { id: 1, name: 'david', age: '45', position: 'teacher' }]; const updateForJames = { age: '38', position: 'project manager' } const JamesId = 2; const jamesobj = myArray.find(({id}) => id === JamesId) || {}; Object.assign(jamesobj, updateForJames); console.log(myArray);
或者,如果您想獲得一個新數組(而不是就地修改它),您可以將每個對象.map()
到一個新對象,並在updateForJames
的 id 出現時使用 spread 語法在updateForJames
添加新內容:
const myArray = [{ id: 1, name: 'john', age: '22', position: 'developer' }, { id: 2, name: 'james', age: '31', position: 'designer' }, { id: 1, name: 'david', age: '45', position: 'teacher' }]; const updateForJames = { age: '38', position: 'project manager' } const JamesId = 2; const new_array = myArray.map( ({id, ...r}) => id === JamesId ? {id, ...r, ...updateForJames} : {id, ...r} ); console.log(new_array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.