簡體   English   中英

如何在對象內部找到數組

[英]How to find array inside object

我有parkingSpots ,它是一個對象數組,它包含一個坐標屬性,它也是一個數組。

例如索引 0:

_id: "5e03c83459d0c115589067ba"
capacity: 2
description: "safas"
title: "aa"
coordinates: (2) [-34.193705512748686, 150.2320126953125]

我試圖找到具有arrayToBeFound的對象。 我嘗試了這個解決方案和許多其他解決方案,但仍然不起作用。

    let arrayToBeFound = [e.latLng.lat(), e.latLng.lng()];
    let selectedParkingSpot = parkingSpots.find(x => x.coordinates === arrayToBeFound);

我一直未定義,但它存在。 有什么幫助嗎?

您需要通過將第一個數組的每個項目與另一個數組的相應項目進行比較來比較兩個數組。 直接將一個數組與另一個數組進行比較是行不通的——它們總是不同的,因為 JS 通過它們的引用來比較數組(對象)。 只有當兩個引用都指向同一個數組時,它們才會相等。 然而,原語是按值比較的。

 let selectedParkingSpot = parkingSpots.find(x => x.coordinates[0] === arrayToBeFound[0] && x.coordinates[1] === arrayToBeFound[1]);

我認為這是最簡單的方法

let selectedParkingSpot = parkingSpots.find(x => x.coordinates[0] === arrayToBeFound[0] && x.coordinates[1] === arrayToBeFound[1]);

您可以使用此處發布的答案,我更喜歡它們,除非您要向該數組添加值,或者在其他數組和/或對象之間執行比較,或者如果您不關心數組的順序。

否則,您可以使用Lodash 的 isEqual來比較對象的值。

 $(document).ready(function() { function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } var arrayOfObjects = [{ _id: "5e03c83459d0c115589067ba", capacity: 2, description: "safas", title: "aa", coordinates: [-34.193705512748686, 160.2320126953125], }, { _id: "5e03c83459d0c115589067ba", capacity: 2, description: "safas", title: "aa", coordinates: [-34.193705512748686, 150.2320126953125], }]; var arrayToBeFound = [-34.193705512748686, 150.2320126953125]; $.each(arrayOfObjects, function(index, object){ if(arraysEqual(arrayToBeFound, object.coordinates)){ console.log(arrayOfObjects[index]); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您無法比較 2 個數組,但如果將它們字符串化,它將起作用。

const data = [
    {
        _id: "5e03c83459d0c115589067ba",
        capacity: 2,
        description: "safas",
        title: "aa",
        coordinates: [-34.193705512748686, 150.2320126953125]
    }
]
const arrayToBeFound = [-34.193705512748686, 150.2320126953125]

let spot = data.find((ele)=>{
    return JSON.stringify(ele.coordinates) === JSON.stringify(arrayToBeFound)
})

// returns the object
console.log(spot)

// returns false
console.log(data[0].coordinates == arrayToBeFound)

//returns true
console.log(typeof data[0].coordinates === typeof arrayToBeFound)

您未定義的原因是因為x.coordinates == arrayToBeFound的比較返回 false,因此 find 不會返回任何東西,並且由於 selectedParkingSpot 沒有值,它將是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM