0

Please can someone explain what the issue is with my code. What I am trying to achieve is to create an array from fruits array (see code block), where array=[name: "Banana", name: "Orange", name: "Apple", name: "Mango"]

var fruits = ["Banana", "Orange", "Apple", "Mango"];
myFunction(fruits)

function myFunction() {
    var array=[];
    var item = {};
    fruits.forEach(function(entry, index){
    item.name=entry

    array.push(item);

});

console.log(array)

}

However when I print array to the console, this is what I get: [[object Object] { name: "Mango" }, [circular object Object], [circular object Object], [circular object Object]]

The first object gets populated correctly, but I don't understand why it is saying there is a circular dependancy for the others. Can anyone please help me to explain what the issue is and how I should resolve it. Thanks!

2 Answers 2

2

[name: "Banana", name: "Orange", name: "Apple", name: "Mango"] isn't a valid JS object, you can homever have:

[{name: "Banana"}, {name: "Orange"}, {name: "Apple}, {name: "Mango"}] which is an array of objects, to do in a loop:

function myFunction() {
  var array=[];

  fruits.forEach(function(entry) {
    array.push({ name: entry });
  });

  console.log(array)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help!
2

You are adding the same object multiple times.

function myFunction() {
  var array=[];

  fruits.forEach(function(entry, index) {
    var item = {};
    item.name=entry

    array.push(item);
  });

  console.log(array)
}

1 Comment

Thanks for your help!

Your Answer

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.