【问题标题】:deep, conditional merge of js objectsjs对象的深度,条件合并
【发布时间】:2018-09-21 23:21:09
【问题描述】:

我正在尝试有条件地将来自两个 http 请求的数据合并到一个对象中。请考虑这些对象。

vehicles: [
{
  vId: 1,
  color: 'green',
  passengers: [
    {
      name: 'Joe',
      age: 22
    },
    {
      name: 'Jack',
      age: 32
    }
  ]
}
more vehicles....]



pDetails: [
  {
    vId: 1,
    detail: tall
  },
  {
    vId: 1,
    detail: 'fat'
  },
  { 
    vId 2,
    detail: 'sad'
  } more details.....
]

两个对象之间的 vId 匹配我想将 pDetails 对象推送到车辆数组中匹配对象的新数组中。我正在使用 Angular 5、TS 并将 Lodash 添加到我的项目中。我对如何遍历嵌套数组感到困惑。我是 JS 新手,对 api 还不是很熟悉。 TS、ES6、Angular 或 Lodash 中有什么东西可以让这更容易吗?

这是我目前为止最接近的:

this.getVehicles().subscribe(
      data => { v = data.result.objects },
      err => console.error(err),
      () => Object.keys(v).forEach(key => {
      console.log(v[key]); //mapping logic here
    })

这成功地遍历了车辆数组,但我想我想做的是整合每个 v.passenger 对象,并为每个对象在 pDetails 数组上进行搜索,复制匹配项,推送到临时数组,然后分配给 v .乘客。我仍然无法弄清楚如何迭代每辆车的乘客数组。

【问题讨论】:

标签: javascript angular typescript ecmascript-6 lodash


【解决方案1】:

使用 rxjs 函数可以帮助您解决此类问题。

这里是使用combineLatest获取车辆详细信息的代码建议(演示代码,未经测试):

// The first observable pushed value would be
// and array of the pushed values by the Observables
combineLatest(this.getVehiclesDetails(),this.getVehicles())
.pipe(
    // Using the returned values, you could transform them to what you want
    map(([vehicules, details]) =>
        // Here we transform our vehicules array to vehiculesWithDetail array
        vehicules.map(vehicule => {
            // We get the detail for the processed vehicule
            const detail = details.find(d => d.vdId == vehicule.vdId);
            // We merge the two objects in one
            return Object.Assign(vehicule, detail);
        })
    )
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多