Javascript 重建对象数组的最佳方法是什么?
我从Kairos人脸检测api获得了这个json对象:Javascript 重建对象数组的最佳方法是什么?,javascript,arrays,object,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}}, {"rightEyeBrowOute
"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);
...
但是如何重新排列它呢?假设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},
// ...
}
假设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},
// ...
}
我不确定是否是dup,但无论如何它都是有用的阅读。你所问的没有意义。您需要或不需要数组,单个元素或多个元素。首先决定你需要什么。数组没有问题。很明显,对于标题中提出的问题,没有单一的一般性答案。我认为执行
p.left眉毛outerleft.x,p.left眉毛outerleft.y
肯定行不通。您可能希望创建一个for循环
,以遍历所有人。向我们展示您的完整JSONY您可以通过编写代码来重新安排它。你被困在哪里了?我不确定,如果是dup,但无论如何它是有用的阅读。你问的没有意义。您需要或不需要数组,单个元素或多个元素。首先决定你需要什么。数组没有问题。很明显,对于标题中提出的问题,没有单一的一般性答案。我认为执行p.left眉毛outerleft.x,p.left眉毛outerleft.y
肯定行不通。您可能希望创建一个for循环
,以遍历所有人。向我们展示您的完整JSONY您可以通过编写代码来重新安排它。你被困在哪里了?谢天谢地,这是一个美丽的解决方案,我自己都想不出来。。。而且它是有效的!:-)谢天谢地,这是一个很好的解决方案,我自己都想不出来。。。而且它是有效的!:-)