0

I parsed a json and I'm trying to take 2 values for each element from the json and put them in a array the problem is that I want to put the values into the array like a single element "array" example:

[
 { name: 'name1', elements: [ 'elem1' ] },
 { name: 'name2', elements: [ 'elem2', 'elem3' ] }
]

I tried 2 ways.

the first is this:

function getMonsters(json) {
 var monsters = [];
 var monster = {};
 json.forEach(element => {
 if (element.type === "large") {
 monster['name'] = element.name;
 monster['elements'] = element.elements;
 monsters.push(monster);
 }
 });
 return monsters;
}

the problem with the first way is that it always returns the same 2 values: response image

the second way is this:

function getMonsters(json) {
 var monsters = [];
 var monster = {};
 json.forEach(element => {
 if (element.type === "large") {
 monsters.push(element.name, element.elements);
 }
 });
 return monsters;
}

but the problem with the second way is that it returns each monster and element separately and not like in my example: response image

this is the json if u want to check : https://mhw-db.com/monsters

Kara
6,23616 gold badges54 silver badges58 bronze badges
asked Apr 18, 2022 at 20:41

2 Answers 2

2

You are reusing the monster object every iteration in your first example. Either move the declaration of var monster = {} into the loop or, better yet, just push an object literal.

function getMonsters(json) {
 const monsters = [];
 json.forEach(({ elements, name, type }) => {
 if (type === "large") {
 monsters.push({ name, elements });
 }
 });
 return monsters;
}
answered Apr 18, 2022 at 20:46
Sign up to request clarification or add additional context in comments.

Comments

2

Your first attempt is almost correct. The reason why all of the items in the array end up being the same object is because monster is the same reference in all of the array items. You need a new instance of monster on every iteration. Just put your initialization of monster in your loop

function getMonsters(json) {
var monsters = [];
json.forEach(element => {
 if (element.type === "large") {
 var monster = {};
 monster['name'] = element.name;
 monster['elements'] = element.elements;
 monsters.push(monster);
 }
});
return monsters;
answered Apr 18, 2022 at 20:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.