0

I have an array that I am looping through and assigning an integer to my variable based off the condition. I would then like to push this variable to my existing array. At the moment, when pushing it is creating a new index. I would like the variable to be included in the existing index of the array. Here is an example of my code:

let data = [{
  "title": "Online",
  "state": "California"
}, {
  "title": "Retail",
  "state": "New York"
}, {
  "title": "Appointments",
  "state": "Florida"
}]

let varInt = 0;
let intArr = []
for (let i = 0; i < data.length; i++) {

  if (data[i].title && data[i].title.includes("Online")) {
    varInt = 1;
    intArr = {
      "varInt": varInt
    }
    data.push(intArr)

    console.log(data)

  }

}

My expected outcome is to have an array that looks like:

data = [{
  "title": "Online",
  "state": "California",
  "varInt": 1
}, {
  "title": "Retail",
  "state": "New York"
}, {
  "title": "Appointments",
  "state": "Florida"
}]
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
stepheniok
  • 395
  • 3
  • 16

2 Answers2

0

you can just declare a new key directly.

let data = [{
  "title": "Online",
  "state": "California"
}, {
  "title": "Retail",
  "state": "New York"
}, {
  "title": "Appointments",
  "state": "Florida"
}]

let varInt = 0;
let intArr = []
for (let i = 0; i < data.length; i++) {

  if (data[i].title && data[i].title.includes("Online")) {
    varInt = 1;
    data[i].varInt = varInt;

    console.log(data)

  }

}
sample
  • 392
  • 2
  • 10
0

f you would like to modify the items in your array that meet a certain condition I'd recommend you use the map function:

let data = [{"title": "Online", "state": "California"}, {"title": "Retail", "state": "New York"}, {"title": "Appointments", "state": "Florida"}]

data = data.map(item=>{
  let meetsCondition = item.title && item.title.includes("Online")
  let varInt = 1
  if(!meetsCondition)
    return item
  else{
    item.varInt = varInt
    return item
  }
})

Or if you must use a for loop:

for (let i = 0; i < data.length; i++) {

if(data[i].title && data[i].title.includes("Online")) {
 varInt = 1; 
 intArr = {"varInt": varInt}
 data[i].intArr = intArr
 
 console.log(data)
 
}

}
PhantomSpooks
  • 2,877
  • 2
  • 8
  • 13