gpt4 book ai didi

javascript - 如何从 es6 中的对象合并并返回新数组

转载 作者:可可西里 更新时间:2023-11-01 02:37:28 24 4
gpt4 key购买 nike

假设有两个对象。

const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']

结果

  {

'1-1':[
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
],
'1-2':[
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
],
'2-1':[
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' },
]
}

基本上,我想对数据进行分组。

我使用 includes 来检查 b 中的项目是否与 a 中的 id 相匹配。然后构造新数组。

这是我的尝试(fiddle):

return b.map(item => a.map(jtem => {
if(jtem.id.includes(item)){
return {
[item]: jtem
}
}
}))

不知何故,它不起作用。

还有,有没有巧妙的方法来避免嵌套的 for 循环或 map 函数?

最佳答案

您可以按照以下步骤进行操作:

  • 对数组b

    应用reduce()
  • 在每次迭代期间,对数组 a

    使用 filter()
  • 使用String.prototype.startsWith() 获取a 中以b 的项目开头的所有项目
  • 最后将其设置为ac的属性并返回ac

const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']

let res = b.reduce((ac,b) => {

ac[b] = a.filter(x => x.id.startsWith(b));
return ac;

},{})
console.log(res)

正如@Falco 所建议的那样,最好在 a 上扫描一次,因为它很大。所以这是那个版本。实际上它在性能方面更好

const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']


let res = a.reduce((ac,x) => {
let temp = b.find(y => x.id.startsWith(y))
if(!ac[temp]) ac[temp] = [];
ac[temp].push(x);
return ac;
},{})

console.log(res)

注意:startsWith 不被 I.E 支持。所以你可以使用 indexOf

创建 polyfill

if(!String.prototype.startWith){
String.prototype.startsWith = function(str){
return this.indexOf(str) === 0
}
}

关于javascript - 如何从 es6 中的对象合并并返回新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com