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']);
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'm looking to extract dict values by key, and I've attempted to add those values to an empty array using the concat() function, however it's printing the values but within their own arrays (atleast it appears that way since each value is surrounded by unique sets of brackets).
var dict = {Name: 'Chris', Height: 150, Location: 'New York'};
var dictVal = new Array();
for (var key in dict) {
var val = dict[key];
console.log(dictVal.concat(val));
}
How do I merge the values so they live within their own single set of brackets to denote the list of values within dictVal?
The mistake that you're making is that Array.concat returns a new array meaning
dictVal = dictVal.concat(val);
is what you want in order to get the result that you want. Alternatively you can also do
for (var key in dict) {
var val = dict[key];
dictVal.push(val);
console.log(dictVal);
}
if you don't want to generate new arrays.
Moreover, there are better ways to do what you want for example mapping the keys of the object to the values:
var dict = {Name: 'Chris', Height: 150, Location: 'New York'};
var dictVal = Object.keys(dict).map(key => dict[key]);
Iterating through Object.keys is usually preferable to a for...in because
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
and Array.map just saves you several lines of code.
Also as a side note using new Array() is generally not common. You'd want to do
var dictVal = []
just to be in better accordance with common JS conventions.
You may do as follows in modern browsers;
var dict = {Name: 'Chris', Height: 150, Location: 'New York'},
dictValues = Object.values(dict);
console.log(dictValues);
I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]
I've got an 'filter' object like
{
name: 'text',
value: 'xxx',
field: 'firstname'
}
which represents a filter for a field and is updated when I change values of input fields.
I try to store this in an array in the following way:
$scope.active_filters[filter.field] = filter;
So that I know on which field I got which filter.
The filtering should happen on server side and so I'm trying to send this array to my API.
$http.post(url, $scope.active_filters)
As I can see in Chrome I've got an array with the desired element in it but length 0
[status: Object]
length: 0
status: Object
field: "status"
name: "text"
value: "x"
__proto__: Object
__proto__: Array[0]
But the object is NOT sent in my request. If I add the object via $scope.active_filters.push(filter) it IS sent to the server but it has the index 0 and not my desired value.
How can I achieve both of my targets? A named index in my array and sending the data to the api.
I'm guessing here but your code is like this:
var assoc_array = [];
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";
JavaScript doesn't know associative arrays like for instance PHP does. JavaScript has objects, and since everything is an object (even arrays) you can get this situation.
Rather than setting the elements in the array you're assigning properties to the object. This means the magical .length property doesn't get updated because the array is still empty.
If you change you code to:
var assoc_array = {}; // <-- {} instead of []
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";
You will get an Object (instead of an Array) and you wont have a .length property.
This is how you would use an Array
var indexed_array = [];
indexed_array[0] = "bar";
indexed_array[1] = "lorem";
indexed_array.length; // 2
indexed_array[100] = "foo";
indexed_array.length; // 101 - arrays are never sparse in JS, PHP will give 3
indexed_array[2]; // undefined
I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.
An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:
var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...
function getItemId(code){
return itemIds[code];
}
What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).
You can use JavaScript object literal syntax:
var itemIds = {
item1: 15,
item2: 40,
item3: 72
};
JavaScript object members can be accessed via dot notation or array subscript, like so:
itemIds.item1;
itemIds['item1'];
You'll need to use the second option if you've got the member name as a string.
Try using Object Literal notation to specify your lookup like this:
var itemIds = {
"item1" : 15,
"item2" : 40
...
};
Access should still work like this:
var item1Value = itemIds["item1"];