我有一个名为 syncWithPreviousDay
的函数,它接收以下对象数组作为属性。
jsonObj
[
{
"Position": "1",
"TrackName": "Rocket",
"URL": "https://domain.local/nbs678"
},
{
"Position": "2",
"TrackName": "Dueling banjos",
"URL": "https://domain.local/asd456"
},
{
"Position": "3",
"TrackName": "One hit wonder",
"URL": "https://domain.local/xyz123"
}
]
在这个函数中,我需要将 key URL
与数据库中具有相同 key 对的另一个对象数组进行比较,并且只要有匹配,就移动 key Position
和 CustomKey
到 data.chart
数组中的新键 PreviousPosition
和 CustomKey
。如果没有匹配项,请为两个键创建一个 null
值。
const syncWithPreviousDay = (jsonObj) => {
const data = {
date: config.dateToday,
chart: jsonObj
}
dbService.getDate(config.yesterday)
.then( result => {
console.log(result.chart)
})
}
console.log
的结果如下所示:
[
{
"Position": "1",
"TrackName": "One hit wonder",
"URL": "https://domain.local/xyz123",
"CustomKey": "x"
},
{
"Position": "2",
"TrackName": "Awesome old song",
"URL": "https://domain.local/123qwe",
"CustomKey": "y"
},
{
"Position": "3",
"TrackName": "Dueling banjos",
"URL": "https://domain.local/asd456",
"CustomKey": null
}
]
所以我想要的data.chart
应该看起来像这样:
[
{
"Position": "1",
"TrackName": "Rocket",
"URL": "https://domain.local/nbs678",
"PreviousPosition": null,
"CustomKey": null
},
{
"Position": "2",
"TrackName": "Dueling banjos",
"URL": "https://domain.local/asd456",
"PreviousPosition": "3",
"CustomKey": null
},
{
"Position": "3",
"TrackName": "One hit wonder",
"URL": "https://domain.local/xyz123",
"PreviousPosition": "1",
"CustomKey": "x"
}
]
如何做到这一点?
最佳答案
您可以简单地通过迭代循环并匹配数据库数组中是否存在特定元素来完成此操作。如果值存在,则添加所需的值,否则添加空值。
我已经向您提供了逻辑,您可以在函数内或任何需要的地方使用它。
const localArr = [
{
"Position": "1",
"TrackName": "Rocket",
"URL": "https://domain.local/nbs678"
},
{
"Position": "2",
"TrackName": "Dueling banjos",
"URL": "https://domain.local/asd456"
},
{
"Position": "3",
"TrackName": "One hit wonder",
"URL": "https://domain.local/xyz123"
}
];
const dbArray = [
{
"Position": "1",
"TrackName": "One hit wonder",
"URL": "https://domain.local/xyz123",
"CustomKey": "x"
},
{
"Position": "2",
"TrackName": "Awesome old song",
"URL": "https://domain.local/123qwe",
"CustomKey": "y"
},
{
"Position": "3",
"TrackName": "Dueling banjos",
"URL": "https://domain.local/asd456",
"CustomKey": null
}
];
for (const element of localArr) {
const index = dbArray.findIndex(item => item.URL === element.URL);
if (index !== -1) {
element.PreviousPosition = dbArray[index].Position;
element.CustomKey = dbArray[index].CustomKey;
} else {
element.PreviousPosition = null;
element.CustomKey = null;
}
}
console.log(localArr)
关于javascript - 比较 2 个 JavaScript 对象并根据条件移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60927225/