如何获取数组中唯一值的属性?
How to get the properties of the unique values in array?
正在编辑问题。从图片中我如何在一个对象中创建一个数组,以便我得到的数据如下:
{ Access Panel: [Step 1, Step 2],
Air Extraction: [Step 1] }
点击数组进行过滤,然后根据文本框中的输入输出唯一的 'Subnames'。我如何循环遍历原始数组,我相信我需要创建 key/value 对?不知道该怎么办。目标是填充 1 'Access Panel' 按钮,以便在单击时填充第 1 步和第 2 步。
已删除照片
使用Array.forEach()
函数:
const arr = [
{subname: "Access Panel", stepnum: "Step 1"},
{subname: "Access Panel", stepnum: "Step 2"},
{subname: "Access Panel", stepnum: "Step 3"},
{subname: "Air Extraction", stepnum: "Step 1"},
{subname: "Air Extraction", stepnum: "Step 2"},
{subname: "Random", stepnum: "Step 1"}
];
const obj = {};
arr.forEach((el) => {
if(!obj[el.subname]){
obj[el.subname] = [el.stepnum];
}else{
obj[el.subname].push(el.stepnum);
}
});
console.log(obj);
更新:
与Array.reduce()
:
const arr = [
{subname: "Access Panel", stepnum: "Step 1"},
{subname: "Access Panel", stepnum: "Step 2"},
{subname: "Access Panel", stepnum: "Step 3"},
{subname: "Air Extraction", stepnum: "Step 1"},
{subname: "Air Extraction", stepnum: "Step 2"},
{subname: "Random", stepnum: "Step 1"}
];
const res = arr.reduce((obj,el) => {
obj[el.subname] = obj[el.subname] ? obj[el.subname].concat(el.stepnum) : [el.stepnum];
return obj;
},{});
console.log(res);
正在编辑问题。从图片中我如何在一个对象中创建一个数组,以便我得到的数据如下:
{ Access Panel: [Step 1, Step 2],
Air Extraction: [Step 1] }
点击数组进行过滤,然后根据文本框中的输入输出唯一的 'Subnames'。我如何循环遍历原始数组,我相信我需要创建 key/value 对?不知道该怎么办。目标是填充 1 'Access Panel' 按钮,以便在单击时填充第 1 步和第 2 步。
已删除照片
使用Array.forEach()
函数:
const arr = [
{subname: "Access Panel", stepnum: "Step 1"},
{subname: "Access Panel", stepnum: "Step 2"},
{subname: "Access Panel", stepnum: "Step 3"},
{subname: "Air Extraction", stepnum: "Step 1"},
{subname: "Air Extraction", stepnum: "Step 2"},
{subname: "Random", stepnum: "Step 1"}
];
const obj = {};
arr.forEach((el) => {
if(!obj[el.subname]){
obj[el.subname] = [el.stepnum];
}else{
obj[el.subname].push(el.stepnum);
}
});
console.log(obj);
更新:
与Array.reduce()
:
const arr = [
{subname: "Access Panel", stepnum: "Step 1"},
{subname: "Access Panel", stepnum: "Step 2"},
{subname: "Access Panel", stepnum: "Step 3"},
{subname: "Air Extraction", stepnum: "Step 1"},
{subname: "Air Extraction", stepnum: "Step 2"},
{subname: "Random", stepnum: "Step 1"}
];
const res = arr.reduce((obj,el) => {
obj[el.subname] = obj[el.subname] ? obj[el.subname].concat(el.stepnum) : [el.stepnum];
return obj;
},{});
console.log(res);