在JavaScript数组中查找对象

时间:2018-07-10 12:56:46

标签: javascript

所以这个问题以前曾被问过,但是我的情况有点不同,因为我已经尝试了该网站中建议的所有解决方案,所以我有一个多维度数组:

var array = [
{
    "dup":{ "lat":36.69507771893455,"lng":2.828052824475776 },
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
{
    "dup":{ "lat":36.69507687630523,"lng":2.8280525056927672},
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
{
    "dup":{ "lat":36.695076,"lng":2.8280523980529324},
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
{
    "dup":{ "lat":36.69507512369477,"lng":2.8280525056927672},
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
{
    "dup":{ "lat":36.69507428106545,"lng":2.828052824475776},
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
{
    "dup":{ "lat":36.695073504493834,"lng":2.828053342151293},
    "original":{ "lat":36.695076,"lng":2.8280580000000555}
},
...
]

还有另一个小数组:

var datax = {"lat":36.69507428106545,"lng":2.828052824475776}

我想要做的就是找到与此“ dup”在同一行中的“原始”。 到目前为止,我尝试过查找,过滤和grep,但这都不能解决我的问题。

我尝试过的代码:

var Cent = $.grep(array, function(e){ return e.dup== JSON.stringify(datax); });
contentString += " and "+Cent +"is the closer";

1 个答案:

答案 0 :(得分:3)

您仍然可以使用Array.filter()来实现:

var array = [{"dup":{"lat":36.69507771893455,"lng":2.828052824475776},"original":{"lat":36.695076,"lng":2.8280580000000555}},{"dup":{"lat":36.69507687630523,"lng":2.8280525056927672},"original":{"lat":36.695076,"lng":2.8280580000000555}},{"dup":{"lat":36.695076,"lng":2.8280523980529324},"original":{"lat":36.69507428106545,"lng":2.828052824475776}},{"dup":{"lat":36.69507512369477,"lng":2.8280525056927672},"original":{"lat":36.695076,"lng":2.8280580000000555}},{"dup":{"lat":36.69507428106545,"lng":2.828052824475776},"original":{"lat":36.695076,"lng":2.8280580000000555}},{"dup":{"lat":36.695073504493834,"lng":2.828053342151293},"original":{"lat":36.695076,"lng":2.8280580000000555}}];
var datax = {"lat":36.69507428106545,"lng":2.828052824475776}

var res = array.filter(item => item.original.lat === datax.lat && item.original.lng === datax.lng);
console.log(res);