我有以下对象对象:
expenditures: {
byId: {
'-LK6x1d5vJxhsbtD4KvF': {
categoryId: 12,
createdAt: 1534510508671,
day: 1534464000000,
description: 'stuff',
updatedAt: 1534510508671,
value: -1.2
},
'-LK6x5tCFOrQZ0nXZO2x': {
categoryId: 13,
createdAt: 1534510526087,
day: 1534464000000,
description: 'food',
updatedAt: 1534510526087,
value: -8.6
},
}
}
我想做的是映射到byId
对象上,并为每个元素将其键作为id
值。像这样:
expenditures: {
byId: {
'-LK6x1d5vJxhsbtD4KvF': {
categoryId: 12,
createdAt: 1534510508671,
day: 1534464000000,
description: 'stuff',
updatedAt: 1534510508671,
value: -1.2,
id: '-LK6x1d5vJxhsbtD4KvF',
},
'-LK6x5tCFOrQZ0nXZO2x': {
categoryId: 13,
createdAt: 1534510526087,
day: 1534464000000,
description: 'food',
updatedAt: 1534510526087,
value: -8.6,
id: '-LK6x5tCFOrQZ0nXZO2x',
},
}
}
我该如何实现?我知道谁可以使用Object.keys()
或Object.values()
来映射对象,但是我不知道如何将键作为值。
答案 0 :(得分:2)
这是使用ES6对象散布算子实现目标的方法。
const expendituresWithId = {
byId: Object.keys(expenditures.byId).map(key => {
return {
[key]: {
...expenditures.byId[key],
id: key
}
}
})
}
使用此解决方案,您无需更改原始对象。
答案 1 :(得分:1)
将每次迭代的密钥存储为另一个属性;您可以使用for..in
,例如:
const expenditures = {
byId: {
'-LK6x1d5vJxhsbtD4KvF': {
categoryId: 12,
createdAt: 1534510508671,
day: 1534464000000,
description: 'stuff',
updatedAt: 1534510508671,
value: -1.2
},
'-LK6x5tCFOrQZ0nXZO2x': {
categoryId: 13,
createdAt: 1534510526087,
day: 1534464000000,
description: 'food',
updatedAt: 1534510526087,
value: -8.6
},
}
}
for (const key in expenditures.byId) {
expenditures.byId[key].id = key
}
console.log(expenditures.byId);
答案 2 :(得分:1)
这是一种解决方案:
Object.keys(expenditures.byId).forEach(id => expenditures.byId[id].id = id)
答案 3 :(得分:0)
这是可以利用ES6某些功能的一种方法:
const expenditures = {
byId: {
'-LK6x1d5vJxhsbtD4KvF': {
categoryId: 12,
createdAt: 1534510508671,
day: 1534464000000,
description: 'stuff',
updatedAt: 1534510508671,
value: -1.2
},
'-LK6x5tCFOrQZ0nXZO2x': {
categoryId: 13,
createdAt: 1534510526087,
day: 1534464000000,
description: 'food',
updatedAt: 1534510526087,
value: -8.6
},
}
};
const updatedExpenditures = Object.entries(expenditures.byId).reduce((accum, kvPair, arr) => {
let [key, value] = kvPair;
accum[key] = Object.assign({
id: key
}, value);
return accum;
}, {});
console.log(updatedExpenditures);