我有两个对象,一个是通过读取 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/