嗨,我想將物件陣列推送到物件陣列,因此新屬性將根據相同的 _id 推送到物件陣列,這是原始資料:
const data =[
{
foo:foo1,
data:{
_id:"a1",
man:2
}
},
{
foo:foo1,
data:{
_id:"a1",
man:2
}
}
]
這是我想放在原始資料中的資料
const d = [{
_id:"a1",
women:4,
}]
所需的輸出是:
const data =[
{
foo:foo1,
data:{
_id:"a1",
man:2,
women:4
}
},
{
foo:foo1,
data:{
_id:"a1",
man:2,
women:4
}
}
]
我認為可以使用 for 回圈并檢查 _id 是否相同并將其推送到物件,但是有沒有更好的方法?還是使用 lodash?任何的想法?提前致謝
uj5u.com熱心網友回復:
你可以試試這個!
const d = [{
_id:"a1",
women:4,
}
]
const data =[
{
foo:"foo1",
data:{
_id:"a1",
man:2
}
},
{
foo:"foo1",
data:{
_id:"a1",
man:2
}
}
]
var arr = data.map(function(obj, i){
d.map(function(o,i){
if(obj.data._id == o._id)
{
obj.data.women = o.women;
}
});
return obj;
});
console.log(arr);
uj5u.com熱心網友回復:
使用您擁有的資料結構,您可以遍歷兩者并簡單地使用相同的id. 也就是說,這是一個具有 O(n^2) 時間復雜度的蠻力解決方案。此解決方案還回傳一個新物件,而不是改變原始物件。
// Existing entries
const entries = [
{
data: {
id: 'a1',
man: 2
}
},
{
data: {
id: 'a1',
man: 2
}
},
];
// Data with same id to update
const updates = [
{
id: 'a1',
women: 4
},
];
/**
* Update properties for an existing entry given
* a list of partially updated entries
*/
function updateEntries(entriesList, updatesList) {
// Build up new array as to not mutate
// the existing data structure
const newEntries = [];
for (const entry of entriesList) {
for (const update of updatesList) {
// Update when the ids match
if (entry.data.id === update.id) {
newEntries.push({
data: {
...entry.data,
...update
}
});
} else {
newEntries.push(entry);
}
}
}
return newEntries;
}
const newEntries = updateEntries(entries, updates);
// newEntries = [
// {
// data: {
// id: 'a1',
// man: 2,
// women: 4
// }
// },
// {
// data: {
// id: 'a1',
// man: 2,
// women: 4
// }
// },
// ];
如果您通過假設它們實際上應該是唯一的而將資料結構更改為entriesto 和 object ,那么您可以獲得 O(n) 基于.entryidupdates
// Entries by id
const entries = {
a1: {
man: 2
},
a2: {
man: 2
},
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463324.html
標籤:javascript 罗达什
