I have a requirement, where i am having a JSON object which should be converted to Key/value pairs array.
JSON:
Object {id: "1213115", transac_status: "Y", trans_id: "601427"....}
This should be converted to JS array like below:
JS Array:
var transData = [{ id: "1213115", transac_status: "Y", trans_id: 601427".... ];
I tried the below script for the conversion.
var transData = $.map(Object , function (e2, e1) {
return [[e2, e1]];
});
The array has not been converted as expected, Instead it has the following :-
Array[2]
,
Array[2]
,
Array[2]
,
Array[2]
..... etc
There is nothing wrong with your code I think. You said, that you want to produce an array with key-value pairs, which you actually do:
Array[2] , Array[2] , Array[2] , Array[2]
This is just the output that console.log produces. If you look closer at your array you'll see, that it actually is:
[["1213115", "id"], ["Y", "transac_status"], ["601427", "trans_id"]]
Thinking about it, you probably might want to switch your key/value pair, like this:
var transData = $.map(Object , function (value, key) {
return [[key, value]];
});
I renamed the function arguments to make things a little clearer.
Output would be:
[["id", "1213115"], ["transac_status", "Y"], ["trans_id, "601427"]]
Tipp: If you are working in a browser, you can just output the whole array with this line, which gives you a nice table-form output:
console.table(transData);
Is that what you are looking for? Hope that helps.
Assuming Object is a list of objects
var arr = [];
$.map(Object, function(item) {
arr.push(item);
});
This will push each object into the array;
Example
Related
I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.
I don't know if this is my little knowledge of jQuery or it is just a bug, but here's what happens. I have this small piece of JSON code
{
"planes":[
{
"id":1,
"name":"Boeing 767-300",
"height":54.9 ,
"wingspan":47.6,
"vel": 851,
"vel max":913,
"plane width":283.3,
"weight":86070,
"full weight":158760,
"passengers":{
"1 class":350,
"2 class":269,
"3 class":218
},
"fuel tank":90.625,
"engine":"2 turbofan General Electric CF6-80C2"
},
{
"id":2,
"name":"Boeing 737-800",
"height":33.4 ,
"wingspan":35.8,
"vel": 840,
"vel max":945,
"plane width":105.44,
"weight":32704,
"full weight":56472,
"passengers":{
"1 class":189
},
"fuel tank":90.625,
"engine":"2 turbofan CFM56-3C1"
}
]
}
which I'm then getting with jQuery's getJSON without any flaw. Then I want two separate arrays: one holding the keys and the other holding the values, and again no problem with Object.keys and Object.values. By logging the result in a single string, everything is fine. Until I try to construct an associative array using keys as indexes and values as data. By logging the result, I get an extra "length" index with value "0". here's my jQuery code
var arr=[];
$.getJSON("js/jsondata.json", function(data){
var keys= Object.keys(data.planes[0]);
var values= Object.values(data.planes[0]);
//im only testing on the first object, for now
$.each(keys, function(i){
//creating the associative index and assigning the value
arr[keys[i]]= values[i];
console.log("Key: "+ keys[i]+", Value: "+values[i]);
//this logs the exact values and indexes
});
console.log(arr);
//this logs an extra "length" 0
});
What you really want to use is a key-value object and not an array. So you have at least to options:
Actually the arrays are objects, and you will be able to attach/add new properties, however, this kind of objects have a pre-defined prototype and properties. One of these properties is length. Cause that, you're getting an "unexpected" property length.
Changing this var arr = []; to this var arr = {};.
Changing this var arr = []; to this var arr = Object.create(null);.
Adding properties to an object array
let arr = [2];
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // 1 cause length is part of Array type.
Adding properties to a key-value object
let arr = {}; // Object.create(null);
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // undefined cause length is not part of the Object type.
Biggest problem is there's no such beast as associative arrays in JavaScript. All arrays must have numbered indices. Association the way you want is handled with objects.
So, you can just assign the first plane in your planes array to a variable and retain your original association rather than iterate it.
Is there a particular reason you're trying to disassemble and reassemble your object to an array this way?
I have the question about js obj order:
When I define:
var objJSON = {};
objJSON[31] = '123'; ------------- (1)
objJSON[23] = '456'; ------------- (2)
And alert the object:
alert(JSON.stringify(objJSON, null, 4));
It shows:
"
{
"23":"456",
"31":"123"
}
"
I would like to get the object by the order of inserting:
"
{
"31":"123",
"23":"456"
}
"
How to do so?
The properties of an object don't have a guaranteed ordering. If the key, value and position is important, I would recommend an array of objects instead:
var x = [];
x.push({
key: 23,
value: '123'
});
x.push({
key: 31,
value: '456'
});
JSON.stringify(x); // [{"key":23,"value":"123"},{"key":31,"value":"456"}]
JavaScript objects cannot be counted on to maintain order. You will likely want to use an array instead, which will preserve index order.
Just change {} to [] in your first line.
var objJSON = [];
You're using an object (which can be thought of as a "map" for this purpose), when you need an array. Objects do not guarantee order. What if you happen to add another property later? It will also skew the order. Try using an array/list/vector of objects instead. For example:
var array = [];
array[0] = { 31: '123' };
array[1] = { 23: '456' };
A dictionary is a data structure that does not preserve order by definition.
You will need to sort the dictionary yourself by key or by value.
Check this:
sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently
try this:
var objList = [];
objList.push({"31" : "123"});
objList.push({"23" : "456"});
alert(JSON.stringify(objList));
You need to put the key-value pairs in an array so you get
{
"array": ["31":"123", "23":"456"]
}
I am trying to create an array in javascript which will allow me to access data like this:
var name = infArray[0]['name'];
however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way.
The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.
JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.
What you want is a mix of both. Something like this:
var infArray = [{
name: 'Test',
hash: 'abc'
}, {
name: 'something',
hash: 'xyz'
}];
Then you can access it like you show:
var name = infArray[0]['name']; // 'test'
or using dot notation:
var name = infArray[0].name; // 'test'
simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)
JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length.
JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:
var myArr = { K1: {
K11: 'K11 val',
K12: 'K12 Val'
},
K2: {
K21: 'K21 Val',
K22: 'K22 Val'
}
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);
If I console log test
I get
[
{
property_1: "a",
property_2: "b",
}
]
How can I console log the value of property_1 ?
console.log(test[0].property_1);
test is an array, who's first element is a map with keys property_1, and property_2.
test[0] accesses the first element of the array, which is a map. From there you can directly access the properties with the dot notation, or with a string subscript:
console.log(test[0]["property_1"]);
console.log(test[0]["property_1"])
First go into the array:
my_arr[0]
Then to get the property:
my_arr[0]['property_1']
End result:
var my_arr = [
{
property_1: "a",
property_2: "b",
}
]
alert(my_arr[0]['property_1']);
If that's what you get when you console.log, then I'd bet that you have a JSON string that needs to be parsed.
If so, do this...
var parsed = JSON.parse(test);
alert(parsed[0].property_1);