andreas rikardo
andreas rikardo

Reputation: 11

How to getting value from array javascript

const array = [
  {
    text: "hello",
    number: 23,
  },
];

const container = document.querySelector(".container");
const btn = document.querySelector(".btn");

btn.addEventListener("click", createText);

function createText() {
  const newText = document.createElement("h1");
  newText.innerText = `${array.text}`;

  container.appendChild(newText);
}

i want to get value text from array? what is wrong? why i get undefined ??

Upvotes: 1

Views: 56

Answers (2)

djcaesar9114
djcaesar9114

Reputation: 2137

array[0].text

But you should change the structure of "array"... For the moment you have an array with only one element, and it's an object.

Either you want to handle an array of objects, or you want to only have one element, in that case you use an object:

const case1 = [
  {
    text: "hello",
    number: 23,
  },
  {
    text: "hello2",
    number: 2345,
  }
];

const case2 = {
  text: "hello",
  number: 23,
}

Upvotes: 0

Anku Singh
Anku Singh

Reputation: 954

Your this code needs to be changed to

newText.innerText = `${array[0].text}`;

Upvotes: 1

Related Questions