将对象与json中的对象进行比较,如果不相同则返回 [英] Compare object to objects in json and return if they are same of not

查看:86
本文介绍了将对象与json中的对象进行比较,如果不相同则返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将填写表单后得到的结果与json返回的属性进行比较.

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);
        });
    });
});

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

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

d.values的我的console.log():

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"}

我想将start_date end_dated.values中的属性进行比较,并希望返回匹配的属性.

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

我希望从上面的比较中返回第三个值({start_date: "2019-12-25", end_date: "2020-04-15"}).

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

我该怎么做?

推荐答案

您可以简单地检查getJSON中的两个值.

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);
    }
  });
 });

另一种方法:

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);
    }
  });
 });

这篇关于将对象与json中的对象进行比较,如果不相同则返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆