如何根据过滤器返回新对象?

时间:2014-10-08 04:23:48

标签: javascript arrays

我有这个js:

var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}

var stuff = json.products.filter(function(obj) {
    return obj.has_ideas === true
});

console.log(stuff);

我需要帮助以与它开始时相同的格式返回一个js obj(var json = {" products":[...}但是只包含过滤后的对象(如果它们存在)。如果没有,我只想要一个空数组。我该怎么做?

1 个答案:

答案 0 :(得分:3)

只需创建您的对象并填写其“产品”属性:

var jsonObj = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}

var stuff = {};
stuff.products = jsonObj.products.filter(function(obj) {
    return obj.has_ideas === true
});

console.log(stuff);