hello
hello

Reputation: 1228

append key value pair to array at a particular index

I have a serializeArray() data populated using:

var compArr = $(':input[name="cc_text"]').serializeArray();

console.log(compArr) looks like this:

0:{name: "cc_text", value: "spring 2016;"}
1:{name: "cc_text", value: "fall 2016;"}

I need to add a new entry such as code: "B007" and code: "J007" into each of the indexes respectively, so that new array looks like:

0:{name: "cc_text", value: "spring 2016;", code: "B007"}
1:{name: "cc_text", value: "fall 2016;", code: "J007"}

Currently, I have a for loop that looks like this:

for(var j = 0; j < countVar; j++)
{
  compArr.push({code: $('#label_text_'+j).text()})
}

The result I get looks like this:

0:{name: "cc_text", value: "spring 2016;"}
1:{name: "cc_text", value: "fall 2016;"}
2:{code: "B007"}
2:{code: "J007"}

When I tried to do something like this inside loop:

compArr[j].push({code: $('#label_text_'+j).text()})

I get error compArr[j].push no push function exists.

Is there a way to achieve this without recreating a new array and reinserting all the data, perhaps by just modifying the how I populate the initial serializeArray()

Upvotes: 0

Views: 759

Answers (2)

MJL
MJL

Reputation: 161

Your compArr contains objects. It looks like you want to add a 'code' property to each of those objects. To do that, loop through compArr and add the appropriate code to each object.

for (var i = 0; i < compArr.length; i += 1) {
    compArr[i].code = $('#label_text_'+i).text();
}

The above example assumes you have #label_text_0 and #label_text_1 elements containing your code values.

Upvotes: 1

Nick
Nick

Reputation: 16576

You're trying to add to an object, not push to an array. Try this:

compArr[j].code = $('#label_text_'+j).text();

Upvotes: 1

Related Questions