Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - How to pull out object within array to new array of object?

Given:

[{
  "date": "2020-12-23",
  "info": [{
      "filled": 4,
    },
    {
      "filled": 10,
    },
  ]
}, {
  "date": "2020-12-30",
  "info": [{
    "filled": 6,
  }]
}]

Desired Result

[
  {
    "filled": 4,
    "date": "2020-12-23"
  },
  {
    "filled": 10,
    "date": "2020-12-23"
  },
  {
    "filled": 6,
    "date": "2020-12-30"
  }
]

How to makes filled value pair with date value?

i can fetch data from GraphQL like this:

[{
  "date": "2020-12-23",
  "info": [{
      "filled": 4,
      "date": "2020-12-23",
    },
    {
      "filled": 10,
      "date": "2020-12-23",
    },
  ]
}, {
  "date": "2020-12-30",
  "info": [{
    "filled": 6,
    "date": "2020-12-30",
  }]
}]

but still unclear how to pair filled with date in one array of objects, because first get fetch data by date then show info, within info thereis date data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do the following,

data = [{
  "date": "2020-12-23",
  "info": [{
      "filled": 4,
      "date": "2020-12-23",
    },
    {
      "filled": 10,
      "date": "2020-12-23",
    },
  ]
}, {
  "date": "2020-12-30",
  "info": [{
    "filled": 6,
    "date": "2020-12-30",
  }]
}]

ret = data.map(item => item.info.map(info => info)).flat();
console.log(ret);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...