Narges Ghasemi
Narges Ghasemi

Reputation: 363

How can i make an array of objects in java script

I want to define an array of objects in JavaScript. object with two properties first is a text and second is a boolean. that at first it is empty and then I add member in array one by one.

myarray = [
{"text1",true},
{"text2",false},
{"text3",false}
];

Upvotes: 4

Views: 148

Answers (3)

Narges Ghasemi
Narges Ghasemi

Reputation: 363

 var myArray = [text1,text2,text3];
  var objArray= [];
  for (let index = 0; index < myArray.length; index++) {
    var newItem = {};
    newItem = {
      name: myArray[index],
      value: true
    }
    objArray.push(newItem);
  }

Upvotes: 4

Rebwar
Rebwar

Reputation: 413

you can create an array and define its data like this:

var myarray = [];
myarray.push({ text: 'text1', boolean: true });
myarray.push({ text: 'text2', boolean: false});
myarray.push({ text: 'text3', boolean: false});

Upvotes: 1

you don't need to define structure before, just add items

let myarray = [];
console.log(myarray);

// one by one
myarray.push({ text: 'text1', boolean: true });
console.log(myarray);

// more at once
myarray = myarray.concat(
    [
        { text: 'text2', boolean: false },
        { text: 'text3', boolean: false }
    ]
);
console.log(myarray);

Upvotes: 0

Related Questions