Compare object to objects in json and return if they are same of not

倾然丶 夕夏残阳落幕 提交于 2020-05-31 04:05:33

问题


I want to compare the results I get back from filling out a form to the properties returned from json.

I am not sure about how to go over that.

This is what I have so far:

$('#btn').on('click', function() {
    let $inputs = $('#new_form :input');
    let new_vals = {};
    $inputs.each(function() {
        new_form[this.id] = $(this).val();
    });

    console.log(new_vals);
    $.getJSON(api, function(data) {
        data.forEach(d => {
            console.log(d.values);
        });
    });
});

My console.log() for new_vals: {start_date: "2019-12-25", end_date: "2020-04-15"}

my console.log() for d.values:

{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2019-12-25", end_date: "2020-04-15"}
{start_date: "2020-03-20", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2020-01-01", end_date: "2020-01-31"}
{start_date: "2020-01-19", end_date: "2020-01-25"}

I want to compare both start_date and end_date to the properties in d.values and want to return the ones that match.

I want the 3rd value ({start_date: "2019-12-25", end_date: "2020-04-15"}) to be returned from the comparison above.

How do I do that?


回答1:


You can simply check the two values inside your getJSON.

 $.getJSON(api, function (data) {
  data.forEach((d) => {
    if(d.values["start_date"] === new_vals["start_date"] && d.values["end_date"] === new_vals["end_date"]) {
      console.log(d.values);
    }
  });
 });

An alternative approach:

isEqualObj = (obj1, obj2) => {
    if(Object.keys(obj1).length !== Object.keys(obj2).length) return false;
    for(key of Object.keys(obj1)) {
        if(obj1[key] !== obj2[key]) return false;
    }
    return true;
}
 $.getJSON(api, function (data) {
  data.forEach((d) => {
    if(isEqualObj(d.values, new_vals)) {
      console.log(d.values);
    }
  });
 });


来源:https://stackoverflow.com/questions/61936471/compare-object-to-objects-in-json-and-return-if-they-are-same-of-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!