使用 Map for 对象值与嵌套在 javascript 中另一个 Map 函数中的数组值配对



我有现有的JSON数据,我想使用map函数构建一个类似的JSON对象,但是嵌套的.map()方法返回的是数据类型,而不是输出的实际数据。

我有这个起始数据:

{
"id": 111,
"other_id": 111,
"name": "name",
"display_name": "display name",
"type": "type",
"required": true,
"sort_order": 0,
"config": {
"config_one": true,
"config_two": true,
"config_three": "weight"
},
"option_values": [
{
"id": 2222,
"other_option_id": 2222,
"label": "Option Value Label",
"sort_order": 0,
"value_data": {
"separate_object_id": 3333
},
"is_default": false,
"adjusters": {
"price": null,
"weight": null,
"image_url": "",
"enable_disable_flag": {
"status": false,
"message": ""
}
}
}
]
}

并希望它在映射函数之后产生此数据:

{
"display_name": "display name",
"type": "type",
"required": true,
"sort_order": 0,
"config": {
"config_one": true,
"config_two": true,
"config_three": "weight"
},
"option_values": [
{
"label": "Option Value Label",
"sort_order": 0,
"value_data": {
"separate_object_id": 3333
},
"is_default": false,
"adjusters": {
"price": null,
"weight": null,
"image_url": "",
"enable_disable_flag": {
"status": false,
"message": ""
}
}
}
]
}

这是我正在使用的当前地图方法函数,它不起作用:

modifier.map(item => {
let returnedItem = {
display_name: item.display_name,
type: item.type,
required: item.required,
sort_order: item.sort_order,
config: item.config,
option_values: item.option_values.map(opt_valItems => ({ 
label: opt_valItems.label, 
sort_order: opt_valItems.sort_order,
value_data: opt_valItems.value_data,
is_default: opt_valItems.is_default,
adjusters: item.adjusters
}))
}  
})

Map总是返回一个新的数组。所以你需要把它赋到一个新变量中。此外,您的代码中还有一个小问题。你在map内使用了let returnedItem,但没有返回任何东西。修复了这个问题。

var modifier = [{
"id": 111,
"other_id": 111,
"name": "name",
"display_name": "display name",
"type": "type",
"required": true,
"sort_order": 0,
"config": {
"config_one": true,
"config_two": true,
"config_three": "weight"
},
"option_values": [
{
"id": 2222,
"other_option_id": 2222,
"label": "Option Value Label",
"sort_order": 0,
"value_data": {
"separate_object_id": 3333
},
"is_default": false,
"adjusters": {
"price": null,
"weight": null,
"image_url": "",
"enable_disable_flag": {
"status": false,
"message": ""
}
}
}
]
}]
var x = modifier.map(item => {
return {
display_name: item.display_name,
type: item.type,
required: item.required,
sort_order: item.sort_order,
config: item.config,
option_values: item.option_values.map(opt_valItems => ({ 
label: opt_valItems.label, 
sort_order: opt_valItems.sort_order,
value_data: opt_valItems.value_data,
is_default: opt_valItems.is_default,
adjusters: item.adjusters
}))
}  
});

console.log(x)

最新更新