简体   繁体   中英

How to compare values in multiple objects

I have an array of objects as below:

var values = [
  [
  {
            "place": {
                "display": "Orlando",
                "value": "ORL"
            },
            "date": {
                "display": "18/07/2021",
                "value": "2021-07-17T23:00:01.000Z"
            }
        },
        {
            "place": {
                "display": "Saint Lucia",
                "value": "SLU"
            },
            "date": {
                "display": "20/07/2021",
                "value": "2021-07-19T23:00:01.000Z"
            }
        }
    ],
    [
        {
            "place": {
                "display": "Saint Lucia"
            },
            "date": {
                "display": "",
                "value": ""
            }
        },
        {
            "place": {
                "display": "Stockholm",
                "value": "STO"
            },
            "date": {
                "display": "",
                "value": ""
            }
        }
    ]
]

How it displays on the front-end:

Row 1:

Place 1: Orlando -- Place 2: Saint Lucia

Row 2:

Place 3: Saint Lucia -- Place 4: Stockholm 

I want to check for each row, more specifically, on the first place of each row (ie Place 1 and Place 3) if places match [array of objects within main array].

So if Place 1 equals Place 3 - return true

This is an example to illustrate the problem. In reality the user can add as many rows as they want so I need to check of each object ( array[0] contains place 1 and place 2 objects; array[1] contains place 3 and place 4 objects and so on and so forth for all the existing objects within the array)

Note: Each row (with 2 places) contains an array of those 2 objects

How to accomplish this in js?

Using flatMap and map you can select the places as an array of string and then compare them as you want:

 var values=[[{place:{display:"Orlando",value:"ORL"},date:{display:"18/07/2021",value:"2021-07-17T23:00:01.000Z"}},{place:{display:"Saint Lucia",value:"SLU"},date:{display:"20/07/2021",value:"2021-07-19T23:00:01.000Z"}}],[{place:{display:"Saint Lucia"},date:{display:"",value:""}},{place:{display:"Stockholm",value:"STO"},date:{display:"",value:""}}]]; var places = values.flatMap(t=>t.map(x=>x.place.display)); console.log(places); //compare any way you want var places = values.flatMap(t => t.map(x => x.place.display)); for (var i = 0; i < places.length - 2; i++) { if (places[i] != places[i + 2]) console.log("place " + (i + 1) + " is not equal to place " + (i + 3)) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM