Reputation: 438
I have a $.post jQuery call that calls a php file. The file then returns a JSON encoded array. Then, the array is mapped to edit some of the data in the array. However, I get the error arr.map is not function
.
Here is the array being passed in the $.post call.
[{"set":"Alpha","key":"256"},
{"set":"Omega","key":"671"},
{"set":"Theta","key":"762"},
{"set":"Beta","key":"462"}]
Here is the map function.
idHash = {'Alpha': '1', 'Beta': '2', 'Theta': '3', 'Omega': '4'};
var arr = arr.map(function(item){
item.set = idHash[item.set]
return item;
})
After the map function, the array should look like this.
[{"set":"1","key":"256"},
{"set":"4","key":"671"},
{"set":"3","key":"762"},
{"set":"2","key":"462"}]
Upvotes: 1
Views: 11966
Reputation: 38787
The array you are executing .map()
would need to be a jquery object. If you set the result data equal to a jquery array with $
affixed to it you should able to use the jquery map utility. You can also use $.map(array, function(item){});
,
https://jsfiddle.net/62v2a0cw/1/
idHash = {'Alpha': '1', 'Beta': '2', 'Theta': '3', 'Omega': '4'};
var arr = $.map(idHash, function(item){
item.set = idHash[item.set];
console.log(item);
return item;
});
Please see jsFiddle link. Let me know if that helps. That is simply to assist with .map()
. If you want to create an array of JSON objects, you could use jQuery .each()
and push each key, value pair accordingly to an array. You could use manipulate the value on each iteration accordingly to your needs. Based on your comments, assuming the JSON you are working with identified by idHash
is equal to {'Alpha': '1', 'Beta': '2', 'Theta': '3', 'Omega': '4'}
arr = [];
idHash = {'Alpha': '1', 'Beta': '2', 'Theta': '3', 'Omega': '4'};
$.each(idHash, function(key, value){
// do whatever with the value before setting
value *= 15;
arr.push({"set": key, "key": value });
});
console.log(arr);
https://jsfiddle.net/62v2a0cw/2/
Upvotes: 8
Reputation: 6236
Signature of .map()
is:
jQuery.map( array, callback )
So, you can try this:
var data = [{"set":"Alpha","key":"256"},
{"set":"Omega","key":"671"},
{"set":"Theta","key":"762"},
{"set":"Beta","key":"462"}];
$.map(data, function(elem){
elem.set = newValue;
elem.key = newValue;
});
Here is the fiddle.
Upvotes: 1