簡體   English   中英

將解構的值從一個數組推送到另一個數組

[英]Push destructured values from one array to another

我對ES6 array.prototype方法有點堅持,並且真的不知道如何正確實現它。 目標是 map 以下 object (假設它被稱為attribues )並將attribute_label值放入一個新數組中。 檢查此值以避免 null 也很重要。 結果應該是一個新數組,其中包含字符串值:

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

您可以使用Object.values從 object 中獲取值:

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

U can use Object.values to create an Array with the content of the Object , then map those values to extract only the attribute_label property and finally filter the Array to skip null values:

 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)

您可以使用 Object.values 和 forEach 推入 label 數組

const attributes_labels = []
Object.values(attributes).forEach(attribute => {
   if (attribute.attribute_label) {
     attributes_labels.push(attribute.attribute_label);
   }
  })

我在這里打敗了一匹死馬,但這是我的解決方案,與其他人的解決方案非常相似:

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM