4

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}
];
2
  • 1
    Post your coding attempt Commented Mar 26, 2020 at 8:33
  • 1
    Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Mar 26, 2020 at 8:34

3 Answers 3

4
 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);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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});

Comments

0

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);

Comments

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.