Home > Software engineering >  I want to merge values of a nested Json object with javascript:
I want to merge values of a nested Json object with javascript:

Time:11-23

So How to merge values of a Json object like this: {"zz0": "value 1","zz1": "value 2","zz2": "value 3"} into this: {"key":["value 1","value 2","value 3"]} In my javascript form this is the first Json file:

    [
        {
            "fotos": [
                {
                    "foto": "foto 1",
                    "zz0": "first line.",
                    "zz1": "second line.",
                    "zz2": "third line."
                },
                {
                    "foto": "foto 2",
                    "zz0": "first line."
                }
            ]
        }
    ]

And this is the second Json File:

    [
        {
            "fotos": [
                {
                    "foto": ["foto 1"],
                    "tekst": ["first line.", "second line.", "third line."]
                },
                {
                    "foto": ["foto 2"],
                    "tekst": ["first line."]
                }
            ]
        }
    ]

Searched a solution with map and arrow functions but got stuck... Any idea?

CodePudding user response:

const arr = [{ "fotos": [{ "foto": "foto 1", "zz0": "first line.", "zz1": "second line.", "zz2": "third line." }, { "foto": "foto 2", "zz0": "first line." }]}];

const ans = arr.map(({fotos}) => ({fotos: fotos.map(({foto, ...res}) =>({foto: [foto], tekst: Object.values(res)}))}));

console.log(ans);

CodePudding user response:

Using Array.map(), Object.keys() anf Array.reduce():

const data = [{
  "fotos": [{
      "foto": "foto 1",
      "zz0": "first line.",
      "zz1": "second line.",
      "zz2": "third line."
    },
    {
      "foto": "foto 2",
      "zz0": "first line."
    }
  ]
}]

const res = data[0].fotos.map(obj => {
  const tekst = Object.keys(obj).reduce((acc,key) => {
    if (key != 'foto') { acc.push(obj[key]) }
    return acc
  }, [])
  
  return { foto: [obj.foto], tekst: tekst }
})

console.log(res)

CodePudding user response:

The following would do the job:

const dat=[
    {
        "fotos": [
            {
                "foto": "foto 1",
                "zz0": "first line.",
                "zz1": "second line.",
                "zz2": "third line."
            },
            {
                "foto": "foto 2",
                "zz0": "first line."
            }
        ]
    }
];

const res=dat[0].fotos.map(f=>({foto:f.foto,key:Object.entries(f).filter(a=>a[0]!='foto').map(a=>a[1])}));

console.log(res);

CodePudding user response:

You could merge them like this with reduce

const a = {a: 2, b: 3, c: 4}
Object.keys(a).reduce((acc, key) => {
    acc['key'].push(a[key])
    return acc
}, {'key': []})

this would give you {'key': [2, 3, 4]}

  • Related