gpt4 book ai didi

javascript - 我怎样才能从中获得特定的 key ?

转载 作者:行者123 更新时间:2023-12-03 00:28:18 24 4
gpt4 key购买 nike

我过去使用过 hasOwnPropertytypeof 但这个难倒了我......我正在尝试获取所有具有匹配键的键,以便我可以将它们与其他键配对示例:

{"meals": [{    
strIngredient1 : lemons
strIngredient2 : paprika
strIngredient3 : red onions
strIngredient4 : chicken thighs
strIngredient5 : vegetable oil
strMeasure1 : 2 Juice
strMeasure2 : 4 tsp
strMeasure3 : 2 finely chopped
strMeasure4 : 16 skinnless
strMeasure5 :
}]}

很明显,strIngredient1strMeasure1 等匹配......任何建议或帮助将不胜感激!

最佳答案

解释

在此示例中,您可以看到我分两部分提供了解决方案,一个是从膳食数组中简单访问 'x' 成分的简单方法,然后是另一个解决方案将迭代一系列膳食,打印出每种成分。

正如我在解决方案中所述,您可以使用 forEach 或者,您也可以使用 mapreduce 等函数如果你希望。如果您不知道何时使用哪个,基本经验法则是,如果满足以下条件,您将使用 mapreduce您希望遵循函数式编程概念。 forEach 解决方案允许更容易发生副作用等...我的意思是这在一定程度上是有争议的,但无论如何这是基本思想...

编辑

我为这个演示添加了一个简单的日志功能,长话短说,当你运行这个代码片段时,我个人觉得控制台窗口提供的空间太少了,这很恶心,所以在之后一次记录一件事一些延迟并清除控制台。

let delay = 0;
const DELAY_INC = 1500;

// Just for this demo, have the ability to log something,
// after a delay and clear the console.
const log = (arg, alrt) => {
setTimeout(() => {
console.clear();
console.log(arg);
if (alrt != null) {
alert(alrt);
}
}, delay);
delay += DELAY_INC;
};

// Your data.
var data = {
"meals": [{
strIngredient1: 'lemons',
strIngredient2: 'paprika',
strIngredient3: 'red onions',
strIngredient4: 'chicken thighs',
strIngredient5: 'vegetable oil',
strMeasure1: '2 Juice',
strMeasure2: '4 tsp',
strMeasure3: '2 finely chopped',
strMeasure4: '16 skinnless',
strMeasure5: ''
}]
};

// Just some demo.
var meals = data.meals;
var meal = meals[0];
var ingredient = meal.strIngredient1;

log(data); // Log the raw data.
log(meals); // Log the array of meals.
log(meal); // Log a specific meal.
log(ingredient); // Log a specific ingredient.

// If you wish to iterate, log each ingredient for each meal.
data.meals.forEach(meal => Object.keys(meal).forEach(key => log(meal[key])));

// Here's a solution.
const newArray = data.meals.reduce((array, meal) => {
// Rather than iterate over ALL of the keys, just
// do this, basically 50% of the keys.
const subArray = Object.keys(meal).filter(key => key.indexOf('strIngredient' == -1));

// Basically add some ojects to the array.
subArray.forEach(key => {
const int = key.replace(/\D/g, '');
const measureKey = `strMeasure${int}`;
const ingredientKey = `strIngredient${int}`;

const obj = {
ingredient: meal[ingredientKey],
measure: meal[measureKey]
};

array.push(obj);
});

// Make sure to return the array.
return array;
}, []);

// Now just print the resuts, and make sure that you know
// and alert that the app has finished.
log(newArray, 'FINISHED');

关于javascript - 我怎样才能从中获得特定的 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com