Reputation: 749
I'm trying to filter JSON with JSON.filter() but my code is wrong, I've tried a few variations and all have failed. Could someone please tell me what I'm doing wrong?
;(async function () {
const result = await transform(xml, template);
const prettyStr = await prettyPrint(xml, { indentSize: 4});
const filterActive = JSON.filter(result, products.active === 'true');
fs.writeFileSync('./temp/converted.json', JSON.stringify(result));
});
Here's the JSON that's output without the filter:
{
"products": [
{
"id": "60000000425",
"sku": "0135363004",
"active": "false",
"brand": "BROWNING",
"description": "725 HUNTER 12G 28\" M/C",
"price": "1719.0000",
"category": "1",
"department": "1"
},
{
"id": "60000000000",
"sku": "00100",
"active": "true",
"brand": "",
"description": "ELEY 22 TENEX",
"price": "0.2600",
"category": "8",
"department": "3"
},
Upvotes: 1
Views: 89
Reputation: 1525
var json_data = {
"products":[
{
"id":"60000000425",
"sku":"0135363004",
"active":"false",
"brand":"BROWNING",
"description":"725 HUNTER 12G 28\" M/C",
"price":"1719.0000",
"category":"1",
"department":"1"
},
{
"id":"60000000000",
"sku":"00100",
"active":"true",
"brand":"",
"description":"ELEY 22 TENEX",
"price":"0.2600",
"category":"8",
"department":"3"
}
]
};
const products = json_data.products;
console.log('*****************');
console.log('Products', products);
console.log('*****************');
const filtered_products = products.filter((prod)=> prod.active === 'true');
console.table(filtered_products);
Upvotes: 0
Reputation: 721
The result might be a string.
Have you tried parsing the result JSON.parse(result)
before doing the filtering ?
And you need to do the filtering like below.
const filterActive = result.products.filter(({active}) => active === 'true');
Upvotes: 1
Reputation: 850
you can only filter an array
change your code to
;(async function () {
const result = await transform(xml, template);
const prettyStr = await prettyPrint(xml, { indentSize: 4});
const filterActive = result.products.filter((product)=>product.active === true);
fs.writeFileSync('./temp/converted.json', JSON.stringify(result));
});
Upvotes: 0
Reputation: 30739
You need to do:
const filterActive = result.products.filter(({active}) => active === 'true');
var result = {
"products": [{
"id": "60000000425",
"sku": "0135363004",
"active": "false",
"brand": "BROWNING",
"description": "725 HUNTER 12G 28\" M/C",
"price": "1719.0000",
"category": "1",
"department": "1"
},
{
"id": "60000000000",
"sku": "00100",
"active": "true",
"brand": "",
"description": "ELEY 22 TENEX",
"price": "0.2600",
"category": "8",
"department": "3"
}
]
};
const filterActive = result.products.filter(({active}) => active === 'true');
console.log(filterActive);
Upvotes: 1