[英]I want to merge values of a nested Json object with javascript:
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:那么如何像这样合并 Json object 的值:
{"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."
}
]
}
]
And this is the second Json File:这是第二个 Json 文件:
[
{
"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?使用 map 和箭头功能搜索解决方案,但卡住了......有什么想法吗?
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);
Using Array.map()
, Object.keys()
anf Array.reduce()
:使用
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)
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);
You could merge them like this with reduce你可以像这样用 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]}
这会给你
{'key': [2, 3, 4]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.