Copy certain key:value pair(s) in a JSON array to a new array

Joe Weinpert
Joe Weinpert used Ask the Experts™
on
javaScript

I have a JSON array passed back to javaScript from a PHP / MS-SQL table extraction.   The table has 100 fields and 2,000 records so the JSON array has 100 "key":"value" pairs and 2,000 rows.

From this JSON array In javaScript, I would like to create another JSON array of all 2,000 rows from it, but with only 2 of its 100 key:value pairs. These two for example (ItemCode and ItemName):

{"ItemCode" : "1234567", "ItemName" : "Widget", "...." : "....", }, { .... }

How can I do that in javaScript?


Another question:

How can I do it being sure there are no duplicates of the 2 key:value pairs in the new array?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David S.Consultant & Challenge Subduer
Top Expert 2009

Commented:
Do you actually use any of the rest of the information in your JS? It seems incredibly inefficient to transfer all of that data for each page request, to only use a little of it.

Anyway, to answer your question, you use a for loop to build a new array or a for-in loop to build a new object (called an "associative array" in other languages).

As to duplicates keys, if there are any, they will overwrite the previous, unless you add additional code to handle that differently.

var myArray2=[];
for(var i=0,k=myArray.length; i<k; i++) {
	myArray2[i]={};
	myArray2[i].prop1=myArray[i].prop1;
	myArray2[i].prop2=myArray[i].prop2;
}

Open in new window

var myObject2={};
for(var key in myObject) {
	myObject2[key]={};
	myObject2[key].prop1=myObject[key].prop1;
	myObject2[key].prop2=myObject[key].prop2;
}

Open in new window

Edit: Typo in code corrected.
Joe WeinpertSr Application Engineer & Developer

Author

Commented:
Oh yes, all of the fields extracted from tables are used in jQWidgets grids.  The purpose of this scenario is to extract just the ItemCode and Description from the main grid to use in a drop-down list.

As to your code, I understand the requirement to loop, but not what you mean by the word key in the first example, or why line 3
myArray[key]={};

Open in new window

is changing the source array.
Consultant & Challenge Subduer
Top Expert 2009
Commented:
I see. Thanks for explaining.

Oh, that was a typo (and I forgot to change "key" to "i" in that example). That line should be:
myArray2[i]={};

Open in new window

Joe WeinpertSr Application Engineer & Developer

Author

Commented:
Ok ... thanks for the input.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial