JSON提取的数据返回太多次

时间:2018-11-30 18:31:34

标签: javascript loops

我有一个大约50个function dz_res_click() { var canvas = document.getElementById("dz_residence_canvas"); var context = canvas.getContext("2d"); var residence = new Image(); residence.src = "../../imgs/residence.jpg" var r_wlaya = document.getElementById("r_wlaya").value; residence.onload = function() { context.drawImage(residence, 0, 0, 2135, 2843); context.font = "bold 70px sans-serif"; context.textAlign = "right"; context.fillText(r_wlaya, 1596, 252); } } 条目的以下形状的JSON:

_source

我只想提取{ "hits": [ { "_source": { "name": "henry", "jobs": ["judge", "lawyer"] } }, { "_source": { "name": "henry", "jobs": ["dev", "waitress"] } } // ... ] } 节点中的第一项,即 jobs,并尝试了以下操作:

judge, dev, ...

我可以提取第一项,但是它出现多次:

for (i in json.hits) 
{ 
    const jobExtract = json.hits[i]._source;        

    for (i=0; i<jobExtract.jobs.length; i++)
    { 
        const firstItem = jobExtract.jobs[0];
        console.log(firstItem);
    }
}

我哪里出错了?

1 个答案:

答案 0 :(得分:2)

我想到的第一个解决方案是使用Reduce

考虑:

const hits =  [
    {
   "_source": {
                "name": "henry",
                 "jobs" : [ "judge","lawyer"] },
     },
     {
   "_source": {
                "name": "henry",
                 "jobs" : [ "dev","waitress"] },
     }, ]

const result = hits.reduce((acc, item) => acc = [item._source.jobs[0], ...acc], []) 

console.log(result) // ["dev", "judge"]

希望这会有所帮助