How to get value in single array not in nested array without any additional operation outside map function.
const List = []
List.push(
{
name: 'John',
id: 383,
Value: [
{
"Age": "10"
},
{
"Age": "20"
}
],
},
{
name: 'Mark',
id: 545,
Value: [
{
"Age": "30"
},
{
"Age": "40"
}
],
}
)
const ageList = List.map((list, index) => {
let age = [];
list.Value.map(item => {
age.push(item.Age)
})
return age
})
console.log(ageList)
Orignal Output : [ [ '10', '20' ], [ '30', '40' ] ]
Expected Output : [10,20,30,40]
CodePudding user response:
This should work well The age array needs to be declared outside
var age=[]
const ageList = List.map((list, index) => {
list.Value.map(item => {
age.push(item.Age)
})
return;
})
console.log(age)
CodePudding user response:
as I understand your code in your age array you are exactly getting the desired result. instead of printing and assigning agelist you can just use the map methods as below
const List = []
List.push(
{
name: 'John',
id: 383,
Value: [
{
"Age": "10"
},
{
"Age": "20"
}
],
},
{
name: 'Mark',
id: 545,
Value: [
{
"Age": "30"
},
{
"Age": "40"
}
],
}
)
List.map((list, index) => {
let age = [];
list.Value.map(item => {
age.push(item.Age)
})
}) console.log(age)
CodePudding user response:
Try this way :
const List = [{
name: 'John',
id: 383,
Value: [
{
"Age": "10"
},
{
"Age": "20"
}]
},{
name: 'Mark',
id: 545,
Value: [
{
"Age": "30"
},
{
"Age": "40"
}
],
}];
const age = [];
List.forEach((list, index) => {
list.Value.forEach(item => {
age.push(item.Age);
})
});
console.log(age);