【发布时间】:2021-09-12 14:54:14
【问题描述】:
需要将其他国家城市数据合并到单个对象中。我的输入如下
result = {
"Bangalore": [
{
"Type": "Sale",
"Date": "2021-07-10",
},
{
"Type": "Product",
"Date": "2021-07-03",
}
],
"Delhi": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"Chennai": [
{
"Type": "Production",
"Date": "2021-06-30",
},
{
"Type": "Production",
"Date": "2021-07-11",
},
],
"Goa": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"sydney": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"melbourne": [
{
"Type": "Product",
"Date": "2021-06-30",
}
]
}
我有其他国家/地区城市数组如下
let arr = [
"sydney",
"melbourne"
]
我试过下面的sn-p它不起作用。
let {sydney,melbourne,...final}=result;
let othercity = [...sydney,...melbourne]
console.log(final)
实际上,当我将变量传递给let {sydney,melbourne,...final} 时,它按预期工作。但我想动态传递这个变量sydney,melbourne。即'让 {...arr,...final}=result;'
预期输出结果: 印度城市
{
"Bangalore": [
{
"Type": "Sale",
"Date": "2021-07-10"
},
{
"Type": "Product",
"Date": "2021-07-03"
}
],
"Delhi": [
{
"Type": "Product",
"Date": "2021-06-30"
}
],
"Chennai": [
{
"Type": "Production",
"Date": "2021-06-30"
},
{
"Type": "Production",
"Date": "2021-07-11"
}
],
"Goa": [
{
"Type": "Product",
"Date": "2021-06-30"
}
]
}
其他城市
{"othercities":[
{
"Type": "Product",
"Date": "2021-06-30"
},
{
"Type": "Product",
"Date": "2021-06-30"
}
]}
如何解决这个破坏性的概念。非常感谢您的回答
let result = {
"Bangalore": [
{
"Type": "Sale",
"Date": "2021-07-10",
},
{
"Type": "Product",
"Date": "2021-07-03",
}
],
"Delhi": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"Chennai": [
{
"Type": "Production",
"Date": "2021-06-30",
},
{
"Type": "Production",
"Date": "2021-07-11",
},
],
"Goa": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"sydney": [
{
"Type": "Product",
"Date": "2021-06-30",
}
],
"melbourne": [
{
"Type": "Product",
"Date": "2021-06-30",
}
]
}
let arr = [
"sydney",
"melbourne"
]
let {sydney,melbourne,...final}=result;
let othercity = [...sydney,...melbourne]
console.log(othercity)
console.log(final)
【问题讨论】:
-
请提供您的所有数据,以及您期望的结果。此外,不需要编写完整的对象,创建一个简单的示例来重现您的问题。
-
你到底想要什么?
-
"message": "SyntaxError: redeclaration of let arr",.. 首先,您的代码需要运行,其次,您希望final是什么? -
如果您不知道解构的具体工作原理,请不要使用解构。它只是语法糖。写出明确的长形式。
-
@Bergi 我更新了我的问题和预期结果
标签: javascript object ecmascript-6 destructuring