Reputation: 473
I want to map and convert the below JSON structure to array of simple string but getting the undefined error while mapping.
JSON structure :
var yourArray = [
{
"options": [
{
'id':1,
'name':'All'
},{
'id':2,
'name':'Javascript'
},{
'id':2000,
'name':'Ruby'
}
]
}
];
Trying to map like this :
var newArray = yourArray.map( function( el ){
yourArray.options.map( function( eln ){
return eln.name;
})
});
console.log (newArray);
Note: Following this example How do I convert a javascript object array to a string array of the object attribute I want?
Upvotes: 0
Views: 1644
Reputation: 37775
Two issues you had in your code
var newArray = yourArray.map( function( el ){
el.options.map( function( eln )
here.yourArray.options
you need to access using index or the el
you're getting in your function call as argument.var yourArray = [{"options": [{'id':1,'name':'All'},{'id':2,'name':'Javascript'},{'id':2000,'name':'Ruby'}]}];
var newArray = yourArray.map( function( el ){
return el.options.map( function( eln ){
return eln.name;
})
});
console.log (newArray);
UPDATE:
Thanks for the answer, sorry to bother you again, My actual JSON structure is like this { "brand": [ {"options": [{"catgeory_name": "Sigma"},{"catgeory_name": "Footner"}]} ] } How can we map this to get the output like this ["Sigma", "Footner"] Because I am still getting undefined error when I map
let data = { "brand": [ {"options": [{"catgeory_name": "Sigma"},{"catgeory_name": "Footner"}]} ] }
let op = data.brand[0].options.map(({catgeory_name})=>catgeory_name)
console.log(op)
Upvotes: 1
Reputation: 6130
here is the simple solution using map, since the option is inside the first index, you can user yourArray[0]
var yourArray = [
{
"options": [
{
'id':1,
'name':'All'
},{
'id':2,
'name':'Javascript'
},{
'id':2000,
'name':'Ruby'
}
]
}
];
var newArray = yourArray[0].options.map(i => i.name)
console.log(newArray)
Upvotes: 0