I have a PHP script that returns a JSON object which looks like this in the console:
[{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]
All I need to do is create another array that contains only the CONTAINER_NUMBER value. It should look like this:
"CONT1234567", "CONT987654"
I found this: http://jsfiddle.net/arunpjohny/ygqaa/
I changed it around to look like the below:
$.POST('phpScript.php', {cntArray:cntArray}, function(data)
{
var containers = JSON.parse(data);
var obj = {};
$.each(containers, function(i, v){
obj[v.CONTAINER_NUMBER]
});
console.log(obj)
});
But the console only shows a blank array.
-
you mean a blank object?user400654– user4006542017年06月29日 19:22:21 +00:00Commented Jun 29, 2017 at 19:22
2 Answers 2
If you just want an object whose keys are the ID:
obj[v.CONTAINER_NUMBER] should be obj[v.CONTAINER_NUMBER] = ''
If you want an array of IDs:
$.post('phpScript.php', {cntArray:cntArray}, function(data)
{
var containers = JSON.parse(data);
var ids = [];
$.each(containers, function(i, v){
ids.push(v.CONTAINER_NUMBER);
});
console.log(ids)
});
Or, a bit cleaner:
$.post('phpScript.php', {cntArray:cntArray}, function(data)
{
var containers = JSON.parse(data);
var ids = $.map(containers, function(i, v){
return v.CONTAINER_NUMBER;
});
console.log(ids);
});
3 Comments
The problem with your code, is that you're passing a value has the key of the object!
var x = {}
x[1]
x[2]
So you get an empty object! But as you mentioned, that's not what you're looking for, you don't want to get an Object, but an Array.
What you can do instead, is to use map and get all the values into an array as you wish! See below:
var json = [{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]
var res = json.map((obj) => obj.CONTAINER_NUMBER)
console.log(res)
Or check the live example,
var json = [{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]
var res = json.map((obj) => obj.CONTAINER_NUMBER)
console.log(res)