0

我对这些ES6 array.prototype方法有点坚持,并不真正知道如何正确实施。目标是映射以下对象(假设它被称为attribues)并将attribute_label值放入一个新数组中。检查此值以避免空值也很重要。结果应该是一个新数组,其中包含字符串值:

{
    "size": {
        "attribute_label": "Size",
        "code": null
    },
    "color": {
        "attribute_label": "Color",
        "code": 24
    },
    "material": {
        "attribute_label": "Material",
        "code": null
    }
}
4

4 回答 4

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"]

于 2021-03-23T17:26:22.083 回答
0

U 可以使用的内容Object.values创建一个,然后映射这些值以仅提取属性,最后过滤以跳过值: ArrayObjectattribute_labelArraynull

const data = {
  "size": {
    "attribute_label": "Size",
    "code": null
  },
  "color": {
    "attribute_label": "Color",
    "code": 24
  },
  "material": {
    "attribute_label": "Material",
    "code": null
  }
};

const values = Object.values(data);
const attributeLabels = values.map(value => value.attribute_label);
const withoutNulls = attributeLabels.filter(label => label !== null);

console.log(withoutNulls)

于 2021-03-23T17:28:03.587 回答
0

您可以使用 Object.values 和 forEach 推入标签数组

const attributes_labels = []
Object.values(attributes).forEach(attribute => {
   if (attribute.attribute_label) {
     attributes_labels.push(attribute.attribute_label);
   }
  })
于 2021-03-23T17:30:12.717 回答
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);

于 2021-03-23T17:33:24.767 回答