I got data where in an array I got set of objects (with country and states keys along with values).
Now, I need to format data in such a manner, that I got a new array (with countryName as key, and list of states -in array as values).
I am trying to do that but unsuccessful. Can someone help me out?
var data = [
{
"country": "United States",
"states": [
"Alabama",
"Alaska",
"Arizona",
]
},
{
"country": "Canada",
"states": [
"Ontario",
"Saskatchewan",
"Alberta",
]
},
{
"country": "Australia",
"states": [
"Australian Capital Territory",
"Jervis Bay Territory",
"New South Wales",
"Queensland",
]
}
];
newData = [];
data.map(item => newData.push({item.country: item.states});
console.log(newData);
That because object key with a dot is not a valid syntax. You can resolve this by wrapping the key with []
. Also, .map()
method creates a new array populated with the results of calling a provided function on every element in the calling array. So, you should either use .forEach()
method here like:
data.forEach(item => newData.push({[item.country]: item.states}));
var data=[{country:"United States",states:["Alabama","Alaska","Arizona"]},{country:"Canada",states:["Ontario","Saskatchewan","Alberta"]},{country:"Australia",states:["Australian Capital Territory","Jervis Bay Territory","New South Wales","Queensland"]}];
var newData = [];
data.forEach(item => newData.push({[item.country]: item.states}));
console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Or, you can use .map()
method and simply return the object inside the .map()
callback and store that in newData
like:
newData = data.map(item => ({[item.country]: item.states}));
var data=[{country:"United States",states:["Alabama","Alaska","Arizona"]},{country:"Canada",states:["Ontario","Saskatchewan","Alberta"]},{country:"Australia",states:["Australian Capital Territory","Jervis Bay Territory","New South Wales","Queensland"]}]
var newData = data.map(item => ({[item.country]: item.states}));
console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Correct use of map
is to return value in map method, which is missing in your code. Apart from that use destructure to further simplify.
const newData = data.map(({country, states}) => ({[country]: states}));
var data = [
{
"country": "United States",
"states": [
"Alabama",
"Alaska",
"Arizona",
]
},
{
"country": "Canada",
"states": [
"Ontario",
"Saskatchewan",
"Alberta",
]
},
{
"country": "Australia",
"states": [
"Australian Capital Territory",
"Jervis Bay Territory",
"New South Wales",
"Queensland",
]
}
];
const newData = data.map(({country, states}) => ({[country]: states}));
console.log(newData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With