javascript - Node JS 如何检查一个对象的所有属性值是否与另一个对象中的相同

标签 javascript json node.js

我有两个对象,一个是通过读取 JSON 文件构建的,另一个是根据作为 url 参数传入的查询构建的,如下所示:

q = req.query.query

它确实有 JSON 数据的子集。例如,通过 JSON.parse() 解析的 JSON 数据可能有如下列表:

boxofficehits.json

[
    {
        "id": "Strawberry swing",
        "artist": "Coldplay",
        "release": "19 Jun, 2009",
        "other entries": ""
        ...
    },
    {
        "id": "No sleep",
        "artist": "Wiz Khalifa",
        "release": "20 April, 2011",
        "other entries": ""
        ...
    }    


]

我的查询对象可能如下所示: var q = {"id": ""草莓秋千"};

我正在通过 require 读取 JSON 文件。

var boxofficehits = require('./boxofficehits.json');

我想返回一个如下所示的对象:

    {
        "id": "Strawberry swing",
        "artist": "Coldplay",
        "release": "19 Jun, 2009",
        "other entries": ""
        ...
    }

除了循环和检查属性的明显方法之外,还有其他方法/库可以用来完成此任务吗?

提前致谢。

最佳答案

检查一致性 ( https://www.npmjs.com/package/congruence )。它完全符合您的要求:

var template = {
  id: 57,
  name: 'Travis'
};
var object = {
  id: 57,
  name: 'Travis',
  color: 'blue',
  foo: 1
};

// the extra object properties are ignored 
assert.isTrue(_.similar(template, object));

您还可以设置模板:

var object = {
  a: 3.1415926535,
  foo: {
    bar: {
      b: 'hello world',
      c: [ 1, 1, 2, 3, 5, 8 ],
      d: new Date()
    }
  }
};
var matchingTemplate = {
  a: 3.1415926535,
  foo: _.congruent({
    bar: _.congruent({
      b: _.isString,
      c: _.isArray,
      d: _.compose(_.not, _.isFunction)
    })
  })
};

assert.isTrue(_.congruent(matchingTemplate, object));

关于javascript - Node JS 如何检查一个对象的所有属性值是否与另一个对象中的相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771166/

相关文章:

ios - 异常 'Invalid type in JSON write (__SwiftValue)' 而 JSON 使用数组编码 Swift 对象

ios - Swift 中的 JSONModel 问题

node.js - 如何从 Nodejs 中的同步 Azure 函数返回结果

javascript - 使用 javascript 修改 ASP.NET DropDownList 时出错

javascript - jquery ajax : call function when all requests are complete

C# 反序列化 JSON html 字符串

javascript - Node - 运行全局安装的自定义模块

node.js - 直线 API : Define a new ChannelId

javascript - 展平数组并丢弃嵌套值

php - 如何屏蔽 IE8 及以下版本?