Search code examples
javascriptarraysmergeconcatenation

react javascript - json how to merge multiple array elements into one string


I have a JSON response as below:

[{
    "id": 1,
    "food": {
      "fruits": ["Banana", "Orange", "Apple", "Mango"],
      "veggies": ["greens", "peppers", "carrot", "potatoes"],
    }
  },
  {
    "id": 2,
    "food": {
      "fruits": ["grapes", "berries", "peach", "pears"],
      "veggies": ["cabbage", "spinach"],
      "dairy": ["nutmilk", "goatmilk"]
    }
  }
]

Now i want to merge the Arrays each "id" (1,2 in example) into string ( ; delimited) like below:

id_1 = Banana;Orange;Apple;Mango;greens;peppers;carrot;potatoes

// observer "id_2" has additional array - "dairy"

id_2 = grapes;berries;peach;pears;cabbage;spinach;nutmilk;goatmilk

The key's are dynamic so for some records there are 2 arrays and for some records it can be 3 or 4 and may be 1.

I tried using react/Java Script Array.concat(), but i am not sure how to do it dynamically. Please help me. Thank you.


Solution

  • This is doable easily using Object.values().flat().join(';') demonstrated below:

    let arr=[{"id":1,"food":{"fruits":["Banana","Orange","Apple","Mango"],"veggies":["greens","peppers","carrot","potatoes"],}},{"id":2,"food":{"fruits":["grapes","berries","peach","pears"],"veggies":["cabbage","spinach"],"dairy":["nutmilk","goatmilk"]}}];
    const result = arr.map(({id,food}) => ({id, food: Object.values(food).flat().join(';')}));
    console.log(result);

    You may easily restructure the output by simply changing it to e.g. ["id_"+id]: Object.values(...)