简体   繁体   English

如何根据另一个数组对象的某些属性创建一个对象数组?

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

This this data:这个这个数据:

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

it's my hope to return an array of objects that populate the non- null values of each strMeasure[n] and strIngredient[n] :我希望返回一个对象数组,这些对象填充每个strMeasure[n]strIngredient[n]的非null值:

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

from cocktail array above, the ideal output would be:从上面的cocktail阵列中,理想的 output 将是:

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

This should do it应该这样做

Use:利用:

  • Object.entries(cocktail[0]) to get an array of [key, value] from the data Object.entries(cocktail[0])从数据中获取 [key, value] 的数组
  • filter to get the Ingredients and Measures - and ignore the ones with null values filter以获取成分和量度 - 并忽略具有null值的那些
  • reduce to build up the resulting array reduce以建立结果数组

Like this:像这样:

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

You could also do it without the filter step您也可以在没有过滤步骤的情况下进行

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

It looks like you could benefit from using javascripts map() method for parsing out the specific key value pairs from within the object in the array.看起来您可以使用 javascripts map() 方法从数组中的 object 中解析出特定的键值对。 There are also several ways you could extract the values you want from inside the object such as through dot notation.还有几种方法可以从 object 中提取所需的值,例如通过点表示法。 I have attached a few links here that are very helpful and will give you a much deeper and basic understanding of how to achieve this.我在此处附上了一些非常有帮助的链接,它们将使您对如何实现这一点有更深入和基本的了解。

From an array of objects, extract value of a property as array 从对象数组中提取属性值作为数组

https://bobbyhadz.com/blog/javascript-convert-array-of-objects-to-array-of-values 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/ https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/

You can first create an array of object which will have measure and id .您可以先创建一个 object 数组,其中包含measureid Then use the id to get the value from cocktail array然后使用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 if you don't mind 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.

相关问题 如何构造一个新的 object 数组,其中包含 JavaScript 中另一个对象数组中的一些已删除属性 - How do I construct a new array of object with some deleted properties from another array of objects in JavaScript 如何根据对象的数组克隆 JavaScript 中的对象 - How can I clone objects in JavaScript based on object's array 如果数组对象的 2 个属性相等,我如何删除数组中的对象? - How can i remove the object in the array if 2 properties of array objects are equal? 如何将对象数组中的某些属性合并到另一个数组中? - How to merge some properties in array of objects into another array? 如何在对象的数组中查找属性并将这些对象移动到对象中的另一个数组? - How find properties in an array in object and move these objects to another array in the object? 如何根据 React/JS 中的另一个数组修改数组的每个对象的属性? - How to modify an array's each object's properties based on another array in React/JS? 如何根据另一个数组中对象的属性创建一个新数组 - How to make a new array based on properties of objects in another array 如何从对象数组创建合并对象,以将原始对象的属性保留为与新传入对象相同的属性 - How can I create a merged object from an array of objects that preserves properties in the original object not changed from the new incoming object 如何基于另一个对象数组创建一个对象数组? - how to create an array of objects based on another array of objects? 根据对象的属性以自定义方式排序 JavaScript 对象数组 - Sort JavaScript array of Objects based on the object's properties in custom way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM