How Do I Extract An Object(array) From An Array Of Objects?
Say I have the following dataset: const art = { 'fields': [ {title:'Title 1'}, {'text': [ {spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'}
Solution 1:
It shouldn't be too hard. Try Javascript's map()
function...
const art = {
'fields': [
{title:'Title 1'},
{'text': [
{spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'}
]},
{title: 'Title 2'},
{title:'Title 3'},
{'text': [
{spaces: '2'}, {link: 'This is a different link'}, {mouse: 'No'}
]},
]};
const spaces = art.fields.map(function(field) {
if(field.text) {
return field.text[0].spaces;
}
return'';
});
console.log("Spaces?");
console.log(spaces);
And the results...
"Spaces?"
["", "1", "", "", "2"]
See the code working on JSBIN. Map returns a function's result for an iteration over an array. Check out the Mozilla Developer Network Docs on it.
Solution 2:
You can use the map
method to calculate a value for each item in the art.fields
array.
const art = {
'fields': [
{title:'Title 1'},
{'text': [
{spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'}
]},
{title: 'Title 2'},
{title:'Title 3'},
{'text': [
{spaces: '2'}, {link: 'This is a different link'}, {mouse: 'No'}
]},
]};
var newArray = art.fields.map(function(o){
return'text'in o ? o.text[0].spaces : '';
});
console.log(newArray);
Solution 3:
you could do something like this
const newArr = art.fields.map(space => {
return {...space.text}
});
so I'm assuming you want to return a new array containing an object of the text array
Solution 4:
if your text array will have multiple spaces then it should loop through it and add in spaces value like below:
const art = {
'fields': [{
title: 'Title 1'
},
{
'text': [{
spaces: '1'
}, {
link: 'This is a link'
}, {
mouse: 'Yes'
}]
},
{
title: 'Title 2'
},
{
title: 'Title 3'
},
{
'text': [{
spaces: '2'
}, {
link: 'This is a different link'
}, {
mouse: 'No'
}]
},
]
};
var res = art.fields.reduce((ini, curr, idx) => {
if (curr.text) {
curr.text.forEach(arr => {
arr.spaces && ini.push(arr.spaces);
});
} else {
ini.push('');
}
return ini;
}, [])
console.log(res);
Post a Comment for "How Do I Extract An Object(array) From An Array Of Objects?"