【问题标题】:Javascript. Compare array of objects, A & B. Return an array that has values from both, prioritizing values from array B [duplicate]Javascript。比较对象数组A和B。返回一个包含两者值的数组,优先考虑数组B中的值[重复]
【发布时间】:2022-01-05 00:18:46
【问题描述】:

给定两个对象数组:

 let a = [
{
  "state": "Alabama"
},
{
  "state": "Alaska"
},
{
  "state": "Arizona"
},
{
  "state": "California"
}
]

let b = [
{
  "state": "Arizona",
  "link": "arizona.com"
},
{
  "state": "Alaska",
  "link": "Alaska.com"
}

如何返回一个由两个数组组合而成的数组,但优先考虑数组 b 中的内容?

示例结果:

result = [
{
  "state": "Alabama"
},
{
  "state": "Alaska",
  "link": "Alaska.com"
}
{
  "state": "Arizona",
  "link": "arizona.com"
},
{
  "state": "California"
}
]

对象是否排序无关紧要。

我最初的想法是创建一个空的结果数组,并将数组'a'中的内容推入其中,而不是数组'b'中的内容。然后,将“b”内的所有内容推入结果数组。 但是,我不确定该怎么做。

谢谢

【问题讨论】:

标签: javascript arrays object


【解决方案1】:
function merge(a, b) {
  if (a.length < b.length) [a, b] = [b, a];

  b.forEach((b) => (a.find((a) => a.state == b.state)['link'] = b.link));
  return a;
}

const result = merge(a, b);

结果:

[
  { state: 'Alabama' },
  { state: 'Alaska', link: 'Alaska.com' },
  { state: 'Arizona', link: 'arizona.com' },
  { state: 'California' }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2021-11-01
    • 2016-10-28
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多