如何将数据推送到嵌套数组中的子数组?

时间:2019-01-28 00:25:27

标签: javascript arrays vanilla-typescript pure-js

尝试构建一个数组,其输出数据如下:

  • 医疗保健
    -数据驱动的见解可改善医疗保健状况
    -Urban Analytics

  • 运输
    -Urban Analytics

  • 城市
    -Urban Analytics

我尝试循环'expertise'/'text',但无法使它们一起工作以在控制台中获得所需的输出。

我们将不胜感激。

    var items = [{
            "item": {
                "id": 0,
                "sector": 'Data',
                "expertise": ["Healthcare"],
                "text": "Data-driven insights to improve healthcare"
            }
        },
        {
            "item": {
                "id": 1,
                "sector": 'Data',
                "expertise": ["Healthcare", "Transport", "Cities"],
                "text": "Urban Analytics"
            }
        }
    }];

    var array = [];

    for (var i = 0; i < items.length; i++) {

        var arr = [{
            'title': items[i].item.sector,
            'items': []
        }];

        for (var j = 0, b = items[i].item.expertise.length; j < b; j++) {
            if (items[i].item.expertise[j] == expertise) {

                arr[0]['items'].push({
                    'list': items[i].item.text
                });

            }
        }

        array.push(arr);

    }

    console.log(array);

3 个答案:

答案 0 :(得分:0)

我将从构建具有相关专业知识和文本列表的对象开始,然后根据需要输出。例如:

var items = [{
  "item": {
    "id": 0,
    "sector": 'Data',
    "expertise": ["Healthcare"],
    "text": "Data-driven insights to improve healthcare"
  }
}, {
  "item": {
    "id": 1,
    "sector": 'Data',
    "expertise": ["Healthcare", "Transport", "Cities"],
    "text": "Urban Analytics"
  }
}]
    
const obj = items.reduce((res, { item }) => {
  item.expertise.forEach(e => {
    res[e] = res[e] || []
    if(res[e].indexOf(item.text) < 0){ res[e].push(item.text) }
  })
  return res
}, {})

Object.keys(obj).forEach(k => {
  console.log(k)
  obj[k].forEach(text => console.log(`-- ${text}`))
})

答案 1 :(得分:0)

您应该使用地图

const array =  items.map(el => ({
    text: el.item.sector,
    items: [...el.item.expertise, {
        list : el.item.text
    }]
});

答案 2 :(得分:0)

这里您使用reduce()的另一种方法,也使用destructuringspread operator

var items = [
  {
    "item": {
      "id": 0,
      "sector": 'Data',
      "expertise": ["Healthcare"],
      "text": "Data-driven insights to improve healthcare"
    }
  },
  {
    "item": {
      "id": 1,
      "sector": 'Data',
      "expertise": ["Healthcare", "Transport", "Cities"],
      "text": "Urban Analytics"
    }  
  }
];

let res = items.reduce((acc, {item: {expertise, text}}) =>
{
     expertise.forEach(x => acc[x] = [...(acc[x] || []), text]);
     return acc;
}, {});


Object.entries(res).forEach(([k, v]) =>
{
    console.log(k + "\n->" + v.join("\n->"));
});