How can I get specific keys from this?
I've used hasOwnProperty
and typeof
in the past but this one is stumping me...
I'm trying to get all the keys that have keys that match so I can pair them with other keys example:
{"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 :
}]}
It's apparent that strIngredient1
matches with strMeasure1
etc...
Any suggestions or help would be greatly appreciated!!
javascript object
|
show 3 more comments
I've used hasOwnProperty
and typeof
in the past but this one is stumping me...
I'm trying to get all the keys that have keys that match so I can pair them with other keys example:
{"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 :
}]}
It's apparent that strIngredient1
matches with strMeasure1
etc...
Any suggestions or help would be greatly appreciated!!
javascript object
2
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
I'm not sure it is apparent thatstrIngredient1
matches withstrMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?
– Tom O.
Dec 31 '18 at 15:15
3
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.
– Shilly
Dec 31 '18 at 15:17
1
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18
|
show 3 more comments
I've used hasOwnProperty
and typeof
in the past but this one is stumping me...
I'm trying to get all the keys that have keys that match so I can pair them with other keys example:
{"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 :
}]}
It's apparent that strIngredient1
matches with strMeasure1
etc...
Any suggestions or help would be greatly appreciated!!
javascript object
I've used hasOwnProperty
and typeof
in the past but this one is stumping me...
I'm trying to get all the keys that have keys that match so I can pair them with other keys example:
{"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 :
}]}
It's apparent that strIngredient1
matches with strMeasure1
etc...
Any suggestions or help would be greatly appreciated!!
javascript object
javascript object
edited Dec 31 '18 at 15:50
Sebastien Kerroue
13514
13514
asked Dec 31 '18 at 15:12
JohnJohn
111111
111111
2
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
I'm not sure it is apparent thatstrIngredient1
matches withstrMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?
– Tom O.
Dec 31 '18 at 15:15
3
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.
– Shilly
Dec 31 '18 at 15:17
1
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18
|
show 3 more comments
2
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
I'm not sure it is apparent thatstrIngredient1
matches withstrMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?
– Tom O.
Dec 31 '18 at 15:15
3
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.
– Shilly
Dec 31 '18 at 15:17
1
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18
2
2
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
I'm not sure it is apparent that
strIngredient1
matches with strMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?– Tom O.
Dec 31 '18 at 15:15
I'm not sure it is apparent that
strIngredient1
matches with strMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?– Tom O.
Dec 31 '18 at 15:15
3
3
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.– Shilly
Dec 31 '18 at 15:17
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.– Shilly
Dec 31 '18 at 15:17
1
1
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18
|
show 3 more comments
2 Answers
2
active
oldest
votes
Explained
In this example, you can see that I've provided the solution in two parts, one being a simple way to simply access 'x'
ingredient from the array of meals, then another solution which will iterate over the array of meals, printing out each individual ingredient.
As I've stated within my solution, you can use forEach
or alternatively, you can also use functions such as map
or reduce
if you wish. In the event that you don't know when to use which, the basic rule of thumb is that you'd use map
or reduce
if you wish to follow functional programming concepts. The forEach
solution allows for side effects to happen more easily, etc... I mean this is debatable to a certain extent, but that's the basic idea anyways...
Edit
I've included a simple log function just for this demo, long story short, when you run this code snippet, personally I find it disgusting how little space is provided for the console window, so log one thing at a time after some delay and clear the console too.
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');
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
|
show 1 more comment
For those interested or if it helps anyone here is the final product! All neat and tidy in one array, easy to use! :) Thank you again JO3-W3B-D3V!
getRecipe: function(url) {
request({
url: url,
method: 'GET'
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
//console.log(result);
// Just some TESTING.
var meals = result.meals; //returns array
var meal = meals[0]; // returns object
//console.log(meal);
// Start here to rename keys and match them to the ingredients.
const newArray = 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));
// console.log(subArray);
// 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 = {
measure: meal[measureKey],
ingredient: meal[ingredientKey]
};
// console.log(obj); //Testing data before
if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
array.push(obj);
// console.log(array); //Testing data after
}
});
const recipeName = meal.strMeal;
const instruction = meal.strInstructions;
const video = meal.strYoutube;
const thumb = meal.strMealThumb;
const nation = meal.strArea;
const category = meal.strCategory;
const recipe = {recipeName, instruction, video, thumb, nation, category};
array.push(recipe);
//console.log(recipe); Testing full array
// 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.
console.log(newArray, "FINISHED");
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53988885%2fhow-can-i-get-specific-keys-from-this%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Explained
In this example, you can see that I've provided the solution in two parts, one being a simple way to simply access 'x'
ingredient from the array of meals, then another solution which will iterate over the array of meals, printing out each individual ingredient.
As I've stated within my solution, you can use forEach
or alternatively, you can also use functions such as map
or reduce
if you wish. In the event that you don't know when to use which, the basic rule of thumb is that you'd use map
or reduce
if you wish to follow functional programming concepts. The forEach
solution allows for side effects to happen more easily, etc... I mean this is debatable to a certain extent, but that's the basic idea anyways...
Edit
I've included a simple log function just for this demo, long story short, when you run this code snippet, personally I find it disgusting how little space is provided for the console window, so log one thing at a time after some delay and clear the console too.
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');
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
|
show 1 more comment
Explained
In this example, you can see that I've provided the solution in two parts, one being a simple way to simply access 'x'
ingredient from the array of meals, then another solution which will iterate over the array of meals, printing out each individual ingredient.
As I've stated within my solution, you can use forEach
or alternatively, you can also use functions such as map
or reduce
if you wish. In the event that you don't know when to use which, the basic rule of thumb is that you'd use map
or reduce
if you wish to follow functional programming concepts. The forEach
solution allows for side effects to happen more easily, etc... I mean this is debatable to a certain extent, but that's the basic idea anyways...
Edit
I've included a simple log function just for this demo, long story short, when you run this code snippet, personally I find it disgusting how little space is provided for the console window, so log one thing at a time after some delay and clear the console too.
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');
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
|
show 1 more comment
Explained
In this example, you can see that I've provided the solution in two parts, one being a simple way to simply access 'x'
ingredient from the array of meals, then another solution which will iterate over the array of meals, printing out each individual ingredient.
As I've stated within my solution, you can use forEach
or alternatively, you can also use functions such as map
or reduce
if you wish. In the event that you don't know when to use which, the basic rule of thumb is that you'd use map
or reduce
if you wish to follow functional programming concepts. The forEach
solution allows for side effects to happen more easily, etc... I mean this is debatable to a certain extent, but that's the basic idea anyways...
Edit
I've included a simple log function just for this demo, long story short, when you run this code snippet, personally I find it disgusting how little space is provided for the console window, so log one thing at a time after some delay and clear the console too.
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');
Explained
In this example, you can see that I've provided the solution in two parts, one being a simple way to simply access 'x'
ingredient from the array of meals, then another solution which will iterate over the array of meals, printing out each individual ingredient.
As I've stated within my solution, you can use forEach
or alternatively, you can also use functions such as map
or reduce
if you wish. In the event that you don't know when to use which, the basic rule of thumb is that you'd use map
or reduce
if you wish to follow functional programming concepts. The forEach
solution allows for side effects to happen more easily, etc... I mean this is debatable to a certain extent, but that's the basic idea anyways...
Edit
I've included a simple log function just for this demo, long story short, when you run this code snippet, personally I find it disgusting how little space is provided for the console window, so log one thing at a time after some delay and clear the console too.
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');
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');
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');
edited Dec 31 '18 at 15:49
answered Dec 31 '18 at 15:23
JO3-W3B-D3VJO3-W3B-D3V
1,487420
1,487420
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
|
show 1 more comment
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Beautiful job parsing them but I still have to match them up... 1 to 1 sort of thing :)
– John
Dec 31 '18 at 15:30
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
Okay, so I have a basic idea here, I'll edit my answer again, if you don't want to or just cannot restructure the data, I have a basic idea that could allow you to get the result you desire.
– JO3-W3B-D3V
Dec 31 '18 at 15:33
1
1
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
That would be really awesome of you, Thank you! I've been fighting with this for 2 days.. Trust me if it were my data I would have never structured it like that!
– John
Dec 31 '18 at 15:40
1
1
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
@John I've updated the answer, I think you'll find that my solution solves your problem? :)
– JO3-W3B-D3V
Dec 31 '18 at 15:49
1
1
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
HUGE thumbs up!! That does indeed answer the question and help greatly, I Thank you so much!!! Great job! Happy New Year......Thanks for taking some terrible data and making it usable!! I can quit pulling my hair out now LOL
– John
Dec 31 '18 at 16:03
|
show 1 more comment
For those interested or if it helps anyone here is the final product! All neat and tidy in one array, easy to use! :) Thank you again JO3-W3B-D3V!
getRecipe: function(url) {
request({
url: url,
method: 'GET'
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
//console.log(result);
// Just some TESTING.
var meals = result.meals; //returns array
var meal = meals[0]; // returns object
//console.log(meal);
// Start here to rename keys and match them to the ingredients.
const newArray = 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));
// console.log(subArray);
// 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 = {
measure: meal[measureKey],
ingredient: meal[ingredientKey]
};
// console.log(obj); //Testing data before
if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
array.push(obj);
// console.log(array); //Testing data after
}
});
const recipeName = meal.strMeal;
const instruction = meal.strInstructions;
const video = meal.strYoutube;
const thumb = meal.strMealThumb;
const nation = meal.strArea;
const category = meal.strCategory;
const recipe = {recipeName, instruction, video, thumb, nation, category};
array.push(recipe);
//console.log(recipe); Testing full array
// 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.
console.log(newArray, "FINISHED");
add a comment |
For those interested or if it helps anyone here is the final product! All neat and tidy in one array, easy to use! :) Thank you again JO3-W3B-D3V!
getRecipe: function(url) {
request({
url: url,
method: 'GET'
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
//console.log(result);
// Just some TESTING.
var meals = result.meals; //returns array
var meal = meals[0]; // returns object
//console.log(meal);
// Start here to rename keys and match them to the ingredients.
const newArray = 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));
// console.log(subArray);
// 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 = {
measure: meal[measureKey],
ingredient: meal[ingredientKey]
};
// console.log(obj); //Testing data before
if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
array.push(obj);
// console.log(array); //Testing data after
}
});
const recipeName = meal.strMeal;
const instruction = meal.strInstructions;
const video = meal.strYoutube;
const thumb = meal.strMealThumb;
const nation = meal.strArea;
const category = meal.strCategory;
const recipe = {recipeName, instruction, video, thumb, nation, category};
array.push(recipe);
//console.log(recipe); Testing full array
// 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.
console.log(newArray, "FINISHED");
add a comment |
For those interested or if it helps anyone here is the final product! All neat and tidy in one array, easy to use! :) Thank you again JO3-W3B-D3V!
getRecipe: function(url) {
request({
url: url,
method: 'GET'
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
//console.log(result);
// Just some TESTING.
var meals = result.meals; //returns array
var meal = meals[0]; // returns object
//console.log(meal);
// Start here to rename keys and match them to the ingredients.
const newArray = 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));
// console.log(subArray);
// 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 = {
measure: meal[measureKey],
ingredient: meal[ingredientKey]
};
// console.log(obj); //Testing data before
if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
array.push(obj);
// console.log(array); //Testing data after
}
});
const recipeName = meal.strMeal;
const instruction = meal.strInstructions;
const video = meal.strYoutube;
const thumb = meal.strMealThumb;
const nation = meal.strArea;
const category = meal.strCategory;
const recipe = {recipeName, instruction, video, thumb, nation, category};
array.push(recipe);
//console.log(recipe); Testing full array
// 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.
console.log(newArray, "FINISHED");
For those interested or if it helps anyone here is the final product! All neat and tidy in one array, easy to use! :) Thank you again JO3-W3B-D3V!
getRecipe: function(url) {
request({
url: url,
method: 'GET'
}, (error, response, body) => {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
//console.log(result);
// Just some TESTING.
var meals = result.meals; //returns array
var meal = meals[0]; // returns object
//console.log(meal);
// Start here to rename keys and match them to the ingredients.
const newArray = 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));
// console.log(subArray);
// 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 = {
measure: meal[measureKey],
ingredient: meal[ingredientKey]
};
// console.log(obj); //Testing data before
if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
array.push(obj);
// console.log(array); //Testing data after
}
});
const recipeName = meal.strMeal;
const instruction = meal.strInstructions;
const video = meal.strYoutube;
const thumb = meal.strMealThumb;
const nation = meal.strArea;
const category = meal.strCategory;
const recipe = {recipeName, instruction, video, thumb, nation, category};
array.push(recipe);
//console.log(recipe); Testing full array
// 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.
console.log(newArray, "FINISHED");
answered Jan 1 at 16:26
JohnJohn
111111
111111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53988885%2fhow-can-i-get-specific-keys-from-this%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Ignoring that this isn't valid JS, it's a bad way of storing that information. Is this your own design, i.e. can you change it?
– Chris G
Dec 31 '18 at 15:14
agree to Chris G, rather let ingredient and measure be properties of the same key
– john Smith
Dec 31 '18 at 15:15
I'm not sure it is apparent that
strIngredient1
matches withstrMeasure1
- do you just mean that all keys are considered "matching" if the names end with the same number?– Tom O.
Dec 31 '18 at 15:15
3
{ "ingredients": [{ "name": "lemons", "measure": "juice", "quantity": 2 }]}
seems way easier to iterate and compare.– Shilly
Dec 31 '18 at 15:17
1
if you cant restructure the data. you could check the overall length of a meal and divide it by two if there´s always a measure for an ingredient and concatinate the key in a loop then ....
– john Smith
Dec 31 '18 at 15:18