user1943674 user1943674 - 15 days ago 7
Javascript Question

Append string to JSON array element in JS

I have a specific format for a set of JSON objects. The format is as follows:

[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}]


I am writing a function using simply JavaScript (no jQuery), that will append a value to the .value element based on if the user input matches a key value. For example, I input key2, the logic will match against key 2, and append "value7" to the end of the value element for that key, resulting in the following:

[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6", "value7"]
}]


Currently the JSON is just an object in the JS file that is parsed using JSON.parse("string"). I would need to perform the appending and then rebuild the JSON using Stringify. (Assuming that would be my logic). I just need help with the appending because I am confused on the logic in this scenario. If anyone could throw together a quick example of how this would look in JS, that would be a massive help. Thank you!

Answer

You't target the object, and then the property containing the array, and push to that array

var array = [{
    "key": ["key1"],
    "value": ["value1", "value2", "value3"]
}, {
    "key": ["key2", "key3"],
    "value": ["value4", "value5", "value6"]
}];

array[1].value.push('value7');

console.log(array);

Comments