在javascript中,我应该如何将jsons附加到变量和另一个json中?

问题描述 投票:1回答:1

这里应该有答案,但我找不到,我有这样的脚本。

 for (count=1;count<5;count++) {
      obj[count]=json[count]
  }

然后我想连接这个 但我是手动做的。

objs=[...obj[1].posts,...obj[2].posts,...obj[3].posts,...obj[4].posts]

我怎么才能自动连接这些东西呢?像这样。

 for (count=1;count<5;count++) {
      obj[count]=json[count]
objs+=[...obj[count].posts]
  }

例如:

var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];

应该得到:

objs=[...obj[1],...obj[2]...obj[3]]
alert(objs)

结果是: 123,456,789。

javascript json
1个回答
0
投票

通过使用: filter & map

var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];

objs = obj.filter(Boolean).map(a=>a[0])

0
投票

对不起,因为我很笨。我用了 objs,push(obj) 与循环。现在我不需要创造价值的循环了。如果你需要的话,我现在用的脚本。

obj=[]
for (count=1;count<5;count++) {
//Your script that gets json
...
//If your json is string (i don't know is every json in internet is string)
      json=JSON.parse(json string that you get
obj.push(...json.posts) //You can change "posts" with array/object (I dont know what is this) that you want or without it if json is  clean array
  }
© www.soinside.com 2019 - 2024. All rights reserved.