簡體   English   中英

如何根據另一個數組對象的某些屬性創建一個對象數組?

[英]How can I create an array of objects based on some of another array object's properties?

這個這個數據:

const cocktail = [
    {
        "idDrink":"13070",
        "strDrink":"Fahrenheit 5000",
        "strGlass":"Shot glass",
        "strInstructions":"Cover bottom of shot gla",
        "strIngredient1":"Firewater",
        "strIngredient2":"Absolut Peppar",
        "strIngredient3":"Tabasco sauce",
        "strIngredient4":null,
        "strMeasure1":"1/2 oz ",
        "strMeasure2":"1/2 oz ",
        "strMeasure3":"1 dash ",
        "strMeasure4":null
    }
]

我希望返回一個對象數組,這些對象填充每個strMeasure[n]strIngredient[n]的非null值:

[
    {
        strMeasure1: value,
        strIngredient1: value
    },
    {
        strMeasure2: value,
        strIngredient2: value
    },
    …
]

從上面的cocktail陣列中,理想的 output 將是:

[
    {
        measure: '1/2 oz',
        name: 'Firewater'
    },
    {
        measure: '1/2 oz',
        name: 'Absolut Peppar'
    },
    {
        measure: '1 dash',
        name: 'Tobasco sauce'
    },
]

應該這樣做

利用:

  • Object.entries(cocktail[0])從數據中獲取 [key, value] 的數組
  • filter以獲取成分和量度 - 並忽略具有null值的那些
  • reduce以建立結果數組

像這樣:

 const cocktail = [ { "idDrink":"13070", "strDrink":"Fahrenheit 5000", "strGlass":"Shot glass", "strInstructions":"Cover bottom of shot gla", "strIngredient1":"Firewater", "strIngredient2":"Absolut Peppar", "strIngredient3":"Tabasco sauce", "strIngredient4":null, "strMeasure1":"1/2 oz ", "strMeasure2":"1/2 oz ", "strMeasure3":"1 dash ", "strMeasure4":null } ] const result = Object.entries(cocktail[0]).filter(([k,v])=>v && k.match(/^str(Ingredient|Measure)\d+$/)).reduce((acc, [k, v]) => { const [t, n] = k.match(/^str(Ingredient|Measure)(\d+)$/).slice(1); acc[n-1] = {...acc[n-1], [t]:v}; return acc; }, []) console.log(result);

您也可以在沒有過濾步驟的情況下進行

const result = Object.entries(cocktail[0])
.reduce((acc, [k, v]) => {
    if (v) {
        const [t, n] = k.match(/^str(Ingredient|Measure)(\d+)$/)?.slice(1) ?? [] ;
        acc[n-1] = {...acc[n-1], [t]:v};
    }
    return acc;
}, [])
console.log(result);

看起來您可以使用 javascripts map() 方法從數組中的 object 中解析出特定的鍵值對。 還有幾種方法可以從 object 中提取所需的值,例如通過點表示法。 我在此處附上了一些非常有幫助的鏈接,它們將使您對如何實現這一點有更深入和基本的了解。

從對象數組中提取屬性值作為數組

https://bobbyhadz.com/blog/javascript-convert-array-of-objects-to-array-of-values

https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/

您可以先創建一個 object 數組,其中包含measureid 然后使用id從 cocktail 數組中獲取值

 const cocktail = [{ "idDrink": "13070", "strDrink": "Fahrenheit 5000", "strGlass": "Shot glass", "strInstructions": "Cover bottom of shot gla", "strIngredient1": "Firewater", "strIngredient2": "Absolut Peppar", "strIngredient3": "Tabasco sauce", "strIngredient4": null, "strMeasure1": "1/2 oz ", "strMeasure2": "1/2 oz ", "strMeasure3": "1 dash ", "strMeasure4": null }] const obj = []; for (let keys in cocktail[0]) { if (keys.includes('strIngredient')) { const tempObj = { measure: cocktail[0][keys], id: keys.charAt(keys.length - 1) } obj.push(tempObj) } } obj.forEach((elem) => elem.value = cocktail[0][`strMeasure${elem.id}`]) console.log(obj)

Lodash如果你不介意的話

 const cocktail = {"idDrink":"13070","strDrink":"Fahrenheit 5000","strGlass":"Shot glass","strInstructions":"Cover bottom of shot gla","strIngredient1":"Firewater","strIngredient2":"Absolut Peppar","strIngredient3":"Tabasco sauce","strIngredient4":null,"strMeasure1":"1/2 oz ","strMeasure2":"1/2 oz ","strMeasure3":"1 dash ","strMeasure4":null}; const parseKey = (str) => [...str.matchAll(/(strIngredient|strMeasure)(\d+)/g)].flat(); const maping = { strIngredient: 'name', strMeasure: 'measure' }; const iter = (acc, value, key) => { const [, keyName, keyNumber] = parseKey(key); if (value && keyName) { acc[keyNumber]??= {}; acc[keyNumber][maping[keyName]] = value; } return acc; }; const result = _(cocktail).transform(iter, {}).values(); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top: 0 }
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

暫無
暫無

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

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