/ / NodeJS come verificare se un oggetto ha tutti i valori di proprietà come in un altro oggetto: javascript, json, node.js

NodeJS come verificare se un oggetto ha tutti i valori appropriati come in un altro oggetto - javascript, json, node.js

Ho due oggetti uno è costruito leggendo un file JSON e un altro è costruito dalla query passata come parametro url simile al seguente:

q = req.query.query

che ha davvero un sottoinsieme di dati JSON. Ad esempio, i dati JSON analizzati tramite JSON.parse () possono avere un elenco come segue:

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


]

Il mio oggetto query potrebbe avere il seguente aspetto: var q = {"id": "" Strawberry swing "};

Sto leggendo il file JSON tramite require.

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

Voglio restituire un oggetto che sarà simile al seguente:

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

Oltre al modo ovvio di eseguire il ciclo e controllare le proprietà, esiste un modo / libreria che posso usare per farlo?

Grazie in anticipo.

risposte:

1 per risposta № 1

Verifica congruenza ( https://www.npmjs.com/package/congruence). Fa esattamente quello che stai cercando:

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

Puoi anche impostare modelli:

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

0 per risposta № 2

Loadsh la libreria fornisce filtro metodo. Il codice seguente funziona:

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

var match={
"id": "Strawberry swing",
"artist": "Coldplay"
};
var result = _.filter(boxofficehits , match);

risultato:

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