0

Есть массив объектов вида:

[
  {
    "name": "Item1",    
    "content": {      
      "groupName": "One"
    }
  },
  {
    "name": "Item2",    
    "content": {      
      "groupName": "One"
    }
  },
  {
    "name": "Item1",    
    "content": {      
      "groupName": "Two"
    }
  }
]

Нужно получить результат в виде:

[
    {
        "group": "One",
        "content": [
            {
                "name": "Item1",    
                "content": {      
                    "groupName": "One"
                }
            },
            {
                "name": "Item2",    
                "content": {      
                    "groupName": "One"
                }
            },
        ]
    },
    {
        "group": "Two",
        "content": [
            {
                "name": "Item1",    
                "content": {      
                    "groupName": "Two"
                }
            }
        ]
    }
]

У меня есть примеры группировки, но не вложенного контента. А тут ума не приложу как пробежаться по вложенному объекту.

1
  • "как пробежаться по вложенному объекту" - .content.groupName
    – user176262
    7 мая 2021 в 12:57

1 ответ 1

1

Нашел решение, надеюсь это одно из. В любом случае может кому-то пригодится для начала.

let input = [{
    "name": "Item1",
    "content": {
      "groupName": "One"
    }
  },
  {
    "name": "Item2",
    "content": {
      "groupName": "One"
    }
  },
  {
    "name": "Item1",
    "content": {
      "groupName": "Two"
    }
  }
]

let result = [];

input.forEach(function(hash) {
  return function(a) {
    if (!hash[a.content.groupName]) {
      hash[a.content.groupName] = {
        group: a.content.groupName,
        content: []
      };
      result.push(hash[a.content.groupName]);
    }
    hash[a.content.groupName].content.push(a);
  };
}(Object.create(null)));

console.log(result);

P.S. "Спасибо" тому кто заминусовал мой вопрос, надеюсь Вы сразу родились экспертом в данной области

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.