Reputation: 487
I have existing JSON data, and I would like to build a similar JSON object using map functions, however the nested .map()
methods are returning the data type and not the actual data for the output.
I have this starting data:
{
"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": ""
}
}
}
]
}
And would like it to result in this data after map function:
{
"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": ""
}
}
}
]
}
This is my current map method function that I'm using, that is not working:
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
}))
}
})
Upvotes: 0
Views: 583
Reputation: 5205
Map
always returns a new Array. So you need to assign this into a new variable. Also, there was a slight problem in your code. You were using let returnedItem
inside the map
, but were not returning anything. Fixed that.
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)
Upvotes: 2