只要键匹配,我想用第二个数组替换第一个数组的值
将用于更新的数组。
[
{
"19": 0,
},
{
"20": 0,
},
{
"21": 0,
},
{
"22": 0,
},
{
"23": 0,
},
{
"24": 0,
},
...
包含用于更新第一个数组的数据的数组。
[
{
"19": 2,
},
{
"20": 1,
},
{
"23": 1,
},
]
我想要获得的结果。
[
{
"19": 2,
},
{
"20": 1,
},
{
"21": 0,
},
{
"22": 0,
},
{
"23": 1,
}
...
这是我写的,但是我无法成功,代码返回一个数组,其中包含所有已更新的值,即使是不应更新的值。
const fakeData = [
{
"createdAt": "2019-09-19T22:51:00.386Z",
"name": "Yank",
},
{
"createdAt": "2019-09-19T22:51:00.386Z",
"name": "Yank",
},
{
"createdAt": "2019-09-20T22:51:00.386Z",
"name": "Yank",
},
{
"createdAt": "2019-09-23T22:51:00.386Z",
"name": "Yank",
}
]
const map = fakeData
.map(item => new Date(item.createdAt).getDate())
.map(item => item)
.reduce((prev, cur) => { prev[cur] = (prev[cur] || 0) + 1; return prev; }, {});
const arrayOfObj = Object.entries(map).map((e) => ({ [e[0]]: e[1] }));
const newArrayWithValueCero = arrayNumberdays.map((item) => ({ [item]: 0 }))
newArrayWithValueCero.map((items, key) => {
const keysOfItems = Object.keys(items)[0] // 1,2,3,4,5,6,7...
const keysOfArrayOfObj = Object.keys(arrayOfObj[key] === undefined ? { "-": "0" } : arrayOfObj[key])[0] // 1,2,3, ------....
return keysOfItems === keysOfArrayOfObj
? { [Object.keys(items)[0]]: Object.values(arrayOfObj[key] === undefined ? { [[Object.keys(items)[0]][0]]: "0" } : arrayOfObj[key])[0] }
: items
})
答案 0 :(得分:1)
您可以执行以下操作:
var list = [
{"19": 0},
{"20": 0},
{"21": 0},
{"22": 0},
{"23": 0},
{"24": 0}
]
var check = [
{"19": 2},
{"20": 1},
{"23": 1},
]
var updateList = check.reduce((acc, val) => {
var key = Object.keys(val)[0];
if(!acc[key]) acc[key] = 0
acc[key] = acc[key] + val[key]
return acc;
},{})
var res = list.map((val) => {
var key = Object.keys(val)[0];
return {
[key]: val[key] + (updateList[key] || 0)
}
})