我对 ES6 array.prototype
方法略有迷惑,不知道如何正确实现它。目标是映射以下对象(假设它称为 attribues
)并将 attribute_label
值放入新数组中。检查此值以避免空值也很重要。结果应该是一个新数组,充满字符串值:
{
"size": {
"attribute_label": "Size",
"code": null
},
"color": {
"attribute_label": "Color",
"code": 24
},
"material": {
"attribute_label": "Material",
"code": null
}
}
答案 0 :(得分:1)
您可以使用 Object.values
从对象中获取值:
const attributes = {
size: {
attribute_label: "Size",
code: null,
},
color: {
attribute_label: "Color",
code: 24,
},
material: {
attribute_label: "Material",
code: null,
},
};
const labels = Object.values(attributes)
.filter((val) => val !== null) // filter out null values
.map(({ attribute_label }) => attribute_label);
console.log(labels);
// ["Size", "Color", "Material"]
如果 attribute_value
本身可以是 null
(而不是对象中的值),只需在末尾添加另一个 .filter()
。
const attributes = {
size: {
attribute_label: "Size",
code: null,
},
color: {
attribute_label: "Color",
code: 24,
},
material: {
attribute_label: "Material",
code: null,
},
another: null,
another_attribute: {
attribute_label: null,
code: null,
},
};
const labels = Object.values(attributes)
.filter((val) => val !== null) // filter out null values
.map(({ attribute_label }) => attribute_label)
.filter((label) => label !== null); // filter out null labels inside the object
console.log(labels);
// ["Size", "Color", "Material"]
答案 1 :(得分:0)
U 可以使用 Object.values
创建一个包含 Array
内容的 Object
,然后映射这些值以仅提取 attribute_label
属性,最后过滤 {{ 1}} 跳过 Array
值:
null
答案 2 :(得分:0)
您可以使用 Object.values 和 forEach 来推入标签数组
const attributes_labels = []
Object.values(attributes).forEach(attribute => {
if (attribute.attribute_label) {
attributes_labels.push(attribute.attribute_label);
}
})
答案 3 :(得分:0)
我在这里打败了一匹死马,但这是我的解决方案,与其他人的解决方案非常相似:
const data = {
size: {
attribute_label: 'Size',
code: null,
},
color: {
attribute_label: 'Color',
code: 24,
},
material: {
attribute_label: 'Material',
code: null,
},
};
const result = Object.values(data)
.map(value => value.attribute_label)
.filter(label => label !== null);