我有以下json数据,并希望将唯一的供应商字段提取到数组中。我如何在angular2组件中完成此任务。
这是我的数据:
[{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Klaussner"},
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Craftmaster"},
{"category": "Living Room", "vendor": "Craftmaster"}]
我想要生成的数组显示:
[{"vendor": "Flexsteel"},
{"vendor": "Klaussner"},
{"vendor": "Craftmaster"}]
答案 0 :(得分:2)
试试这个:
const data = [...your data...];
const vendors = data.map(d => {
return { vendor: d.vendor };
});
答案 1 :(得分:2)
您可以使用Array.map:
let data = [
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Klaussner"},
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Craftmaster"}
];
let processedData = data.map(dat => ({ vendor: dat.vendor }));
答案 2 :(得分:2)
首先你需要得到供应商,你可以这样得到它:
let data = [{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Klaussner"},
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Craftmaster"}];
// Get all the vendors
let vendors = data.map(dat => ({ vendor: dat.vendor }));
之后,您需要过滤供应商,并且只能使用以下独特供应商:
// Unique Vendors
let uniqueVendors= Array.from(new Set(vendors.map((x) => JSON.stringify(x))))
.map((y) => JSON.parse(y.toString()));
完整的代码段:
let data = [{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Klaussner"},
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Craftmaster"}];
// Get all the vendors
let vendors = data.map(dat => ({ vendor: dat.vendor }));
let uniqueVendors= Array.from(new Set(vendors.map((x) => JSON.stringify(x))))
.map((y) => JSON.parse(y.toString()));
console.log(uniqueVendors)