-1
data1 = [{name:"sonu",roll:34,file:"asj.jpg"},  {name:"sonu",roll:34,file:"asj1.jpg"},{name:"sonu",roll:34,file:"asj2.jpg"},{name:"dip",roll:67,file:"fgd3.jpg"},
    {name:"dip",roll:67,file:"fgd4.jpg"},
    {name:"dip",roll:67,file:"fgd5.jpg"}] 

"data" json convert to like "data2"

 data2= [{name:"sonu",roll:34,file:[asj.jpg,asj1.jpg,asj2.jpg]},
{name:"dip",roll:67,file:[fgd3.jpg,fgd.jpg,fgd5.jpg]}]
  • 1
    What have you tried, and how did it fail? What specific problem are you facing with your code? – re-za Mar 21 '22 at 11:17
  • [Duplicate](//google.com/search?q=site:stackoverflow.com+js+merge+arrays+in+object+by+id) of [Merge objects with same id in array](/q/58692417/4642212). Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212) and use the static and instance methods of [`Object`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Mar 21 '22 at 11:18

1 Answers1

0

Use Array.reduce() to reduce the first array into what you want:

const data = [
    { name: "sonu", roll: 34, file: "asj.jpg" },
    { name: "sonu", roll: 34, file: "asj1.jpg" },
    { name: "sonu", roll: 34, file: "asj2.jpg" },
    { name: "dip", roll: 67, file: "fgd3.jpg" },
    { name: "dip", roll: 67, file: "fgd4.jpg" },
    { name: "dip", roll: 67, file: "fgd5.jpg" }
]

const data2 = data.reduce((prev, curr) => {
    const found = prev.find(o => o.name === curr.name)
    found ?
        found.file.push(curr.file)
        : prev.push({ ...curr, file: [curr.file] })

    return prev
}, [])


console.log(data2);
re-za
  • 750
  • 4
  • 10