我有一個陣列如下:
[
{
"id":1,
"active":1,
"name":"paris"
},
{
"id":2,
"active":0,
"name":"london"
},
{
"id":3,
"active":1,
"name":"Australia"
},
{
"id":4,
"active":0,
"name":"india"
}
]
我有一個接收物件作為引數的方法。物件看起來像這樣:
{
"id":4,
"active":0,
"name":"india"
}
在該方法中,我想檢查是否存在具有特定 id 的元素。如果存在,我想用引數中收到的元素替換陣列中的元素。如果未找到具有該 id 的元素,則將該元素添加到陣列中。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
你可以這樣做
let testArr = [
{
id: 1,
active: 1,
name: "paris",
},
{
id: 2,
active: 0,
name: "london",
},
{
id: 3,
active: 1,
name: "Australia",
},
{
id: 4,
active: 0,
name: "india",
},
];
let testObj = {
id: 4,
active: 0,
name: "india1",
};
let findIndex = testArr.findIndex((data) => data.id === testObj.id);
if (findIndex != -1) {
testArr[findIndex].active = testObj.active;
testArr[findIndex].name = testObj.name;
} else {
testArr = [...testArr, testObj];
}
console.log("testArr=>", testArr);
uj5u.com熱心網友回復:
我提出以下建議:無論如何,您都希望將新物件包含在給定陣列中:
- 從陣列中洗掉具有 id 的物件
- 添加新物件
可以如下作業:
let testArr = [ ... ]
let testObj = { ... }
testArr = testArr.filter(element => element.id !== testObj.id)
testArr.push(testObj)
如果有必要將物件保留在陣列中:
let testArr = [ ... ]
let testObj = { ... }
const foundElement = testArr.find(element => element.id === testObj.id)
if (foundElement) {
foundElement.active = testObj.active
foundElement.name = testObj.name
} else {
testArr.push(testObj)
}
uj5u.com熱心網友回復:
你可以做這樣的事情
const update = (data, item) => {
const withId = data.reduce((res, curr) => ({
...res,
[curr.id]: curr
}), {})
withId[item.id] = item
return Object.values(withId)
}
let testArr = [
{
id: 1,
active: 1,
name: "paris",
},
{
id: 2,
active: 0,
name: "london",
},
{
id: 3,
active: 1,
name: "Australia",
},
{
id: 4,
active: 0,
name: "india",
},
];
let testObj = {
id: 4,
active: 0,
name: "india1",
};
const updated = update(testArr, testObj)
console.log(updated)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/493997.html
標籤:javascript 数组
上一篇:JS陣列與陣列物件的交集
