我有一个大约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);
}
}
我哪里出错了?
答案 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"]
希望这会有所帮助