Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  73] [ 2]  / answers: 1 / hits: 27388  / 13 Years ago, thu, august 11, 2011, 12:00:00

I have a JSON array like this:



_htaItems = [
{ID:1,
parentColumnSortID:0,
description:Precondition,
columnSortID:1,
itemType:0},
{ID:2,
parentColumnSortID:0,
description:Precondition,
columnSortID:1,
itemType:0}]


I want to update this by passing the ID, column name and new value to a function:



    function updateJSON(ID, columnName, newValue)
{
var i = 0;
for (i = 0; i < _htaItems.length; i++)
{
if (_htaItems[i].ID == ID)
{
?????
}
}
}


My question is, how do I update the value? I know I can do something like the following:



 _htaItems[x].description = 'New Value'


But in my cause, the column name is being passed as a string.


More From » json

 Answers
18

In JavaScript, you can access an object property either with literal notation:



the.answer = 42;


Or with bracketed notation using a string for the property name:



the[answer] = 42;


Those two statements do exactly the same thing, but in the case of the second one, since what goes in the brackets is a string, it can be any expression that resolves to a string (or can be coerced to one). So all of these do the same thing:



x = answer;
the[x] = 42;

x = ans;
y = wer;
the[x + y] = 42;

function foo() {
return answer;
}
the[foo()] = 42;


...which is to set the answer property of the object the to 42.



So if description in your example can't be a literal because it's being passed to you from somewhere else, you can use bracketed notation:



s = description;
_htaItems[x][s] = 'New Value';

[#90675] Wednesday, August 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johannatorim

Total Points: 599
Total Questions: 124
Total Answers: 100

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;