简体   繁体   中英

How to compare different objects in the same array in javascript

I have sample data. I want to compare objects in array that i do not have all the data. if object not contain specific properties like in this given data i have missed params property in one object and rooms propertx missed in one object so i have to pull these two from common data.

What i have tried here

var emptyvar = [];

    var totalYears = hello.reduce(function (accumulator, pilot) {
      if (JSON.stringify(accumulator) != JSON.stringify(pilot)) {
        emptyvar.push(pilot)
      }
    });

but this compares whole object rather than only keys. How can i get missing data.

[  
       {  
          "coords":{  
             "lat":"52.5013632",
             "lon":"13.4174913"
          },
          "params":{  
             "rooms":"5",
             "value":"1000000"
          },
          "street":"Adalbertstraße 13"
       },
       {  
          "coords":{  
             "lat":"52.4888151",
             "lon":"13.3147011"
          },
          "params":{  
             "value":"1000000"
          },
          "street":"Brandenburgische Straße 10"
       },
       {  
          "coords":{  
             "lat":"52.5141632",
             "lon":"13.3780111"
          },
          "params":{  
             "rooms":"3",
             "value":"1500000"
          },
          "street":"Cora-Berliner-Straße 22"
       },
       {  
          "coords":{  
             "lat":"52.5336332",
             "lon":"13.4015613"
          },
          "street":"Fehrbelliner Straße 23"
       }
    ]

There are a bunch of json schema validators out there, one of them popular at this time is ajv

you can find an example working with your schema, you can tweak it depending on which properties are required and whether additional keys can be accepted

const schema = {
    $id: 'home',
    properties: {

        coords: {
            properties: {
                lat: { type: 'string' },
                lon: { type: 'string' }
            },
            required: ['lat', 'lon']
        },

        params: {
            properties: {
                rooms: { type: 'string' },
                value: { type: 'string' }
            }
        },

        street: { type: 'string' }
    },

    required: ['coords', 'params', 'street'],
    additionalProperties: false
};

const ajv = new Ajv({
    schemas: [schema]
});

let data = { 
  coords:{  
     lat: "52.5013632",
     lon:"13.4174913"
  },
  params:{  
     rooms:"5",
     value:"1000000"
  },
  street:"Adalbertstraße 13"
};


console.log(ajv.validate(schema, data));

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