根据嵌套对象数组中的键组合对象数组的结果

问题描述

我有一组对象,我想根据特定的 id 过滤和组合结果。这是示例:

[
    {
        id: 1,items: [
            {
                id: 10,values: [11],},{
                id: 20,values: [13,14,15],],{
        id: 2,values: [12],];

这是预期的结果:

[
    {
        id: 10,values: [11,12],{
        id: 20,];

我还需要过滤重复项。谢谢

注意:如果我想要这个结果怎么办?

[
    {
        // here I want value for id 10 (it will be always one number)
        value: 11,// here I want values for id 20 (array of numbers) => remove possible duplicates
        values: [13,{
        // here I want value for id 10 (it will be always one number)
        value: 12,];

我用 Map 尝试了相同的方法,但没有成功。基本上我想根据 id 组合值。

解决方法

  1. 您可以使用 Array.flatMap 过滤单个数组中的所有 items
  2. 然后使用 Array.reduce 重新创建数组并将基于 id 的值推送到新的值对象中
  3. 并使用 Array.filter 忽略数组中的重复值
  4. Object.values 只返回数组格式的对象值

年长

const arr = [ { id: 1,items: [ { id: 10,values: [11],},{ id: 20,values: [13,14,15],],{ id: 2,values: [12],];


const res = Object.values(arr.flatMap(({items})=> items)
           .reduce((acc,{id,values})=>{
              acc[id] = acc[id] ?? {id,values:[]}; 
              //check the object exist or not 

              let newArr = acc[id]['values'].concat(values);
              let valArr = newArr.filter((v,i)=>newArr.indexOf(v) === i)
              //remove the duplicates

              acc[id]['values'] = valArr
             return acc
          },{}))

console.log(res)

更新

const arr = [ { id: 1,];


function filterMethod(arr,value,values){
return arr.map(({items})=> ({
              value:detector(items,value)[0],values:detector(items,values)
        }))
}

function detector(items,idVal){
  let ind = items.findIndex(({id})=> id === idVal);
  return ind > -1 ? items[ind]['values'] : ['']
}
         
console.log(filterMethod(arr,10,20))