简体   繁体   中英

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.

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 eg ["id_"+id]: Object.values(...)

First flatten using map , flat and join . Then convert the resulting array of objects to a single object using assign .

 var db = [{"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"]}}]; var flat = db.map( ({id, food}) => ({[`id_${id}`]: Object.values(food).flat().join(';')}) ); var result = Object.assign(...flat); console.log(result);

This is really two problems: looping through an array of objects to combine them into one object, and looping through an object to concat all of its array.

Tackling the second one first, something like this would work:

 const concatArraysInObject = obj => Object.values(obj).reduce((result, arr) => result.concat(arr), []); const input = { a: [1,2,3], b: [4,5,6], c: [7,8,9] }; const output = concatArraysInObject(input); console.log(output);

Object.values() will give you an array of all arrays in an object.

The reduce() function takes a two parameters: a function and initial value.

The function should also take (at least) 2 parameters: the result of the last call (or initial value) and the current value in the array.

It'll call the function once for each element in the array.

Now, with that solved, we can tackle the first problem.

For this, we can also use reduce() as well, and we'll construct our combined object on each call.

 const concatArraysInObject = (obj) => Object.values(obj).reduce((result, arr) => result.concat(arr), []); const mergeObjectsInArray = (arr, dataKey) => arr.reduce((result, obj) => ({ ...result, [obj.id]: concatArraysInObject(obj[dataKey]) }), {}); const input = [ { id: 'A', data: { a: [1,2,3], b: [4,5,6] } }, { id: 'B', data: { c: [7,8,9], d: [10,11,12] } } ]; const output = mergeObjectsInArray(input, 'data'); console.log(output);

An important note of warning: object key order is NOT guaranteed in JavaScript. While 99% of the time they will be in the order you expect, this is not a guarantee, so if you depend on the order of the keys for the order of the array (if order matters), you'll want to change your input structure. If order doesn't matter, it is probably fine how it is.

Try this using basic for loop. Inside you will compute key dynamically and value being flattened array of Object.values of the iterating object.

 var input = [{ 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"] } } ]; var temp = []; for (var i = 0; i < input.length; i++) { temp.push({ [`id_${input[i].id}`]: Object.values(input[i].food) .flat(1) .join(";") }); } console.log(temp); // this gives you an array console.log(Object.assign(...temp));// in case you require one single object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM