如何在React Native中将数组对象转换为对象

时间:2019-07-13 05:48:29

标签: javascript json react-native object arrayobject

我调用了API Called并像这样获取数组。

0:
2019-07-25: {title: "Sub task for 11"}
__proto__: Object
1: {2019-07-19: {…}}
2: {2019-07-24: {…}}
3: {2019-07-26: {…}}
4: {2019-07-25: {…}}
5: {2019-07-24: {…}}
6: {2019-07-25: {…}}
7: {2019-07-25: {…}}

我想将上面的对象数组转换为对象。如下所示。

     "2019-07-25": {title: "Sub task for 11"},
     "2019-07-19": {title: "Sub task for 12"},
     "2019-07-24": {title: "Sub task for 13"},
     "2019-07-26": {title: "Sub task for 14"}

我尝试过,但不能这样转换。请任何人知道如何转换此帮助我。谢谢

2 个答案:

答案 0 :(得分:2)

您可以像这样使用Object.assign()spread syntax

const input = [
  { "2019-07-25": { title: "Sub task for 11" } },
  { "2019-07-19": { title: "Sub task for 12" } },
  { "2019-07-24": { title: "Sub task for 13" } }
];

const output = Object.assign({}, ...input)

console.log(output)

答案 1 :(得分:1)

您可以使用reduce来实现

var res = [
  { "2019-07-25": { title: "Sub task for 11" } },
  { "2019-07-19": { title: "Sub task for 12" } },
  { "2019-07-24": { title: "Sub task for 13" } }
].reduce((a, b) => ({ ...a, ...b }))
     
console.log(res)