我想用javascript合并嵌套Json对象的值:

knpiaxh1  于 2022-11-26  发布在  Java
关注(0)|答案(4)|浏览(141)

如何像这样合并Json对象的值:{"zz0": "value 1","zz1": "value 2","zz2": "value 3"}转换为:{"key":["value 1","value 2","value 3"]}在我的javascript表单中,这是第一个Json文件:

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

这是第二个Json文件:

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

搜索了一个带有Map和箭头功能的解决方案,但被卡住了...有什么想法吗?

h79rfbju

h79rfbju1#

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);
wwodge7n

wwodge7n2#

使用Array.map()Object.keys()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)
qco9c6ql

qco9c6ql3#

下面的代码可以完成这项工作:

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);
p4rjhz4m

p4rjhz4m4#

您可以使用reduce像这样合并它们

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

这将给予{'key': [2, 3, 4]}

相关问题