Группировать по похожему атрибуту и ​​объединять их через запятую javascript - PullRequest
0 голосов
/ 03 мая 2018

Мне нужно сгруппировать массив ниже с похожим типом и отделить каждое описание запятой.

Введите

let obj=[
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test1"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  }
]

выход

let finalobj=[
  {
    "type": "Bedroom",
     "description": "Test,Test1,Test"
  },
  {
    "type": "Bathroom",
    "description": "Test,Test,Test"
  }
]

Моя попытка (я довольно близка, но в первом сете получаю неопределенность)

let obj=[
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test1"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  }
]
//first take the type
let type_only=obj.map(o=>o.type);
type_only=Array.from(new Set(type_only));

let sum_obj={};
let arr=[];
//iterate types

{type_only.map((val,index) =>{
    sumobj = obj.reduce((c, v) => v.type === val ? {'description': (c.description + ','+ v.description),'type':v.type} : c, 0)
    arr.push(sumobj);
    }
    )}

console.log(arr);
console.log(type_only);

Ответы [ 4 ]

0 голосов
/ 03 мая 2018

Вы можете использовать array#reduce с Map.

let arr = [ { "type": "Bedroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" }, { "type": "Bedroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test1" }, { "type": "Bedroom","int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" }, { "type": "Bathroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" }, { "type": "Bathroom", "int_input": 1, "enum_input": 0, "enum_select":"Yes", "description": "Test" }, { "type": "Bathroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" } ],
    result = [...arr.reduce((map,{type, description}) => {
      map.has(type) ? map.get(type).description += ', ' + description : map.set(type, {type, description});
      return map;
    },new Map).values()];
console.log(result);
0 голосов
/ 03 мая 2018

Попробуйте выполнить

let obj=[
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test1"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  }
]
//first take the type
let type_only=obj.map(o=>o.type);
type_only=Array.from(new Set(type_only));

let sum_obj={};
let arr=[];
//iterate types

{type_only.map((val,index) =>{
    // c is an object, append description only and not object
    // Also, check for blank description while appending
    sumobj = obj.reduce((c, v) => v.type === val ? {'description': (c.description ? c.description + ','+ v.description : v.description),'type':v.type} : c, 0)
    arr.push(sumobj);
    }
    )}

console.log(arr);
console.log(type_only);
0 голосов
/ 03 мая 2018

Используйте Reduce, создайте базовый объект, если он не существует в аккумуляторе, и добавьте текущее описание. Используйте Object.values() для преобразования обратно в массив:

const obj = [{"type":"Bedroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test"},{"type":"Bedroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test1"},{"type":"Bedroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test"},{"type":"Bathroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test"},{"type":"Bathroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test"},{"type":"Bathroom","int_input":1,"enum_input":0,"enum_select":"Yes","description":"Test"}];

const result = Object.values(obj.reduce((r, { type, description }) => {
  r[type] = r[type] || { type, description: '' };
  
  r[type].description += `${r[type].description ? ' ,' : ''}${description}`;
  
  return r;
}, Object.create(null)));

console.log(result);
0 голосов
/ 03 мая 2018

Просто reduce в объект, группируем по типу, а затем отображаем обратно в массив объектов:

const input=[
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test1"
  },
  {
    "type": "Bedroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  },
  {
    "type": "Bathroom",
    "int_input": 1,
    "enum_input": 0,
    "enum_select": "Yes",
    "description": "Test"
  }
];
const outputObj = input.reduce((accum, { type, description }) => {
  if (!accum[type]) accum[type] = description;
  else accum[type] += ',' + description;
  return accum;
}, {});
const output = Object.entries(outputObj).map(([ type, description]) => ({ type, description }));
console.log(output);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...