4

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);
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • 2
    That is an improper usage of `map()`. You use `map()` when you want the result to accumulate translations and return them all in an array to be stored in a variable. Your instance is not doing that and is simply using it to iterate. You should use `forEach()` instead. – Taplar Apr 14 '20 at 15:26
  • ForEach is old and TLs ask to avoid it -- in favor of .map() or .filter(); – Deadpool Apr 14 '20 at 15:27
  • Also if you want your keys to have periods in them, you need to quote them, such as `{'item.country': 'my value'}` – Taplar Apr 14 '20 at 15:27
  • Not sure what age of a function has to do with anything. It works perfectly fine. Otherwise, use map properly. – Taplar Apr 14 '20 at 15:28
  • @Deadpool What is "TLs"? But yes, when you avoid `forEach`, you should also avoid `push`. Use the return value of `map`! – Bergi Apr 14 '20 at 15:30
  • @Deadpool Surely TLs need a lesson in JS again :) With their logic `for` is even older and should never be used at all – Anurag Srivastava Apr 14 '20 at 15:30
  • @AnuragSrivastava There are much better [reasons to avoid `forEach`](https://stackoverflow.com/a/49420944/1048572) than its age. – Bergi Apr 14 '20 at 15:33

6 Answers6

8

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; }
palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

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);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
1

You can try this:
It works well with your requirements.

data.forEach(item => {
    const obj = new Object();
    obj[item.country] = item.states;
    newData.push(obj)
});

Here we are using the new keyword to declare our Object and just pushing the object into our Array. Also, since country is a variable so we are using the [] notation rather than the dot notation.

Rajat Verma
  • 301
  • 2
  • 13
0

Try like this.

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",
        ]
    }
];


let newData = data.map(item => { return { [item.country] : [...item.states]}})
console.log(newData);
Sayooj V R
  • 2,255
  • 2
  • 11
  • 23
0

let arr = []
array.forEach(element => {
  arr.push({key:element.country, value: element.state})
}

**if you use map then please return but i think you use forEach in such case

arslan
  • 1,064
  • 10
  • 19
0

please use for loop, for async await condition, map not working well.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 16 '23 at 00:38