重构对象数组的最佳方法是什么?

时间:2016-12-24 11:12:42

标签: javascript arrays object

我从Kairos面部检测api得到了这个json对象:

"landmarks":[
    {"leftEyeBrowOuterLeft":{"x":38,"y":76}},
    {"leftEyeBrowInnerLeft":{"x":47,"y":74}},
    {"leftEyeBrowInnerRight":{"x":56,"y":76}},
    {"leftEyeBrowOuterRight":{"x":65,"y":80}},
    {"rightEyeBrowOuterLeft":{"x":78,"y":78}},
...
    {"lowerLipTopInnerLeft":{"x":68,"y":139}}]

要绘制它,我不知道如何以另一种方式访问​​数据:

var p=json.frames[0]["people"][0]["landmarks"];
 context.beginPath();  
 context.lineTo(p[0].leftEyeBrowOuterLeft.x,p[0].leftEyeBrowOuterLeft.y);
 context.lineTo(p[3].leftEyeBrowOuterRight.x,p[3].leftEyeBrowOuterRight.y);
 context.stroke();

我想最好的方法是摆脱阵列结构?所以它看起来像这样:

...
context.lineTo(p.leftEyeBrowOuterLeft.x,p.leftEyeBrowOuterLeft.y);
...

但我如何重新安排它?

1 个答案:

答案 0 :(得分:2)

假设API返回的数组包含问题中具有单个属性的对象,并且没有重复属性名称,您只需使用.reduce()将数组折叠为对象:

var landmarkProps = json.frames[0].people[0].landmarks.reduce(function(o, l) {
  var properties = Object.keys(l);
  // should be just one, but just in case check for all properties
  properties.forEach(function(prop) {
    // it would be an error here for o[prop] to be already set,
    // so one could check for that if the API might do that
    o[prop] = l[prop];
  });
  return o;
}, {});

这将为您留下一个包含数组中所有地标属性的对象,而无需索引到数组中。结果是landmarkProps看起来像:

{
  "leftEyeBrowOuterLeft": {"x":38,"y":76},
  "leftEyeBrowInnerLeft": "x":47,"y":74},
  "leftEyeBrowInnerRight": {"x":56,"y":76},
  "leftEyeBrowOuterRight": {"x":65,"y":80},
  "rightEyeBrowOuterLeft": {"x":78,"y":78},
  // ...
}