【问题标题】:Find matches between an Array and an Objects' array [closed]查找数组和对象数组之间的匹配项[关闭]
【发布时间】:2020-07-14 10:02:00
【问题描述】:

我有一个博客,里面有一些文章。 每个用户都有一个名为“favorites”的道具,它是一组最喜欢的帖子。当用户点击每个帖子中放置的“心形图标”时,帖子的名称将添加到用户属性中。

我想在个人资料页面上创建一个部分,用户可以在其中查看他们添加到收藏夹的帖子。为此,我必须将 USER 的 ARRAY 与 POSTS 的 ARRAY 匹配。

    userFavoritesArray = ['post1', 'post2', 'post5', ...]
    postsArray = [
      { title: 'post1', 
        desc: 'hello'
      },
      ...
    ]

示例:

user: {
favorites: ['post1']
}

posts: [
{name: 'post1', desc: 'yo bro'},
{name: 'post2', desc: 'hello im the post2'},
{name: 'post3', desc: 'good morning'}
]

我希望这个用户的输出是favorites: [{name: 'post1', desc: 'yo bro'}]

【问题讨论】:

  • 你能举一个你所追求的输出的例子吗?
  • 请添加想要的结果。和你的尝试。
  • @NinaScholz 我编辑主题

标签: javascript arrays vue.js object match


【解决方案1】:

你的问题并不完全清楚,但我猜你想要的是这样的:

const input = ['a', 'c']
const database = [
  { title: 'a', foo: 1 },
  { title: 'b', foo: 2 },
  { title: 'c', foo: 3 }
]
const output = mapByTitle(database, input)
console.log(output)
// Result: [ { title: 'a', foo: 1 }, { title: 'c', foo: 3 }]

在这种情况下,您可以使用Array.prototype.find(它将遍历一个数组,直到找到您的回调为其返回true然后返回该元素的元素)和Array.prototype.map(它将去通过一个数组并返回一个新数组,其中所有元素都映射到每个元素的回调的返回值)。

例如:

// Usage of `find`:
console.log(database.find(item => item.title === 'a'))
// Result: { title: 'a', foo: 1 }
console.log(database.find(item => item.title === 'z'))
// Result: undefined

// Usage of `map`:
console.log(['hello', 'world'].map(item => item.toUpperCase() + '!'))
// Result: ['HELLO!', 'WORLD!']

那么,我们可以像这样构建上述mapByTitle 函数:

function mapByTitle (database, input) {
  return input.map(title => database.find(item => item.title === title))
}

【讨论】:

  • 嗨,是的,你找到了我。太感谢了!我顺便编辑了话题。
猜你喜欢
  • 1970-01-01
  • 2020-07-04
  • 2012-06-20
  • 2021-07-08
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多