我有一个像
这样的对象
{ -L1Rm6VbfLLyFJ3Qi6K: {city: "Tokyo", date: "26-08-2004" } }
我想这样改变这个对象:
{ id:"-L1Rm6VbfLLyFJ3Qi6K", city: "Tokyo", date: "26-08-2004" }
我该怎么做?谢谢...
您可以采用 object.entries 和 MAP 以所需格式。
let obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } }
let op = Object.entries(obj).map(([key,value]) => ({
id: key,
...value,
}))
console.log(op)
如果只有一个对象/索引,则可以以这种方式访问。
let obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } }
let op = Object.entries(obj).map(([key,value]) => ({
id: key,
...value,
}))
console.log(op[0])
如果对象将成为一个键值,则使用此功能,否则,例如@code maniac建议,您应该使用地图或foreach
const obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } }
const newobj = {
id: Object.keys(obj)[0],
...obj[Object.keys(obj)]
}
console.log(newobj)
也许您看起来像这样?
const obj1 = { "-L1Rm6VbfLLyFJ3Qi6K": {city: "Tokyo", date: "26-08-2004" } }
const obj2 = {}
for (const id in obj1) {
Object.assign(obj2, { id, ...obj1[id] })
}
console.log(obj2);
或以这种方式重复旧对象?
const obj1 = { "-L1Rm6VbfLLyFJ3Qi6K": {city: "Tokyo", date: "26-08-2004" } }
for (const id in obj1) {
Object.assign(obj1, { id, ...obj1[id] })
delete obj1[id];
}
console.log(obj1);