0

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

  • 医疗保健
    ——改善医疗保健的数据驱动洞察
    ——城市分析

  • 交通
    ——城市分析

  • 城市
    ——城市分析

我已经尝试循环“专业知识”/“文本”,但我无法让它们一起工作以在 console.log 中获得所需的输出

任何和所有的帮助将不胜感激。

    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);
4

3 回答 3

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}`))
})

于 2019-01-28T00:38:02.570 回答
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->"));
});

于 2019-01-28T01:43:06.707 回答
0

你应该使用地图

const array =  items.map(el => ({
    text: el.item.sector,
    items: [...el.item.expertise, {
        list : el.item.text
    }]
});
于 2019-01-28T00:45:13.493 回答