I got a realy simple question:
Take a look at this JSON String:
this.objects = [{"pid":"2","x":"10","y":"10"}]; // only one i know
Now i would like to adress an object out of it like so:
this.objects.pid[2]
I know thats pointless in this case as you would access it like:
this.objects[0]
The thing is that i need to adress an object array in JSON by the object id and not the array index. Is there a nice approach to this?
Thanks!
function getObject(id, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].pid == id) {
return array[i]
}
}
}
A function that takes your id and array and returns your object. Basically loop through the array and find the element with your id. This can be optionally cached for speed increase.
It doesn't need to be a single element array, so try this...
this.objects = {"pid":"2", "x":"10", "y":"10"};
And you can read it either of these ways:
this.objects.pid;
this.objects['pid'];
If you wanted multiple lists of x,y,etc. then try something like this:
this.objects = { "2": {"x": "10", "y": "10"} };
this.objects["2"].x;
this.objects["2"]["x"];
Essentially, in this case, just use the "pid" as they key for each object that contains the properties you want for each item.
Related
I have an object through which im trying to loop through using for..in. But it gives me "0" as values instead of the object keys such as piidata, location, risklevel etc.
var srcObj = [{
location: "34",
piidata: "sdafa",
risklevel: "Medium"
}]
for (var prop in srcObj) {
console.log(prop);
}
srcObj is an array, as evidenced by the []. Inside it is an object at index 0.
Your "srcObj" is an array. This is indicated by the wrapping [ ... ]. If you console.log srcObj[0], you should get the object itself.
while you are looping the javascript object it's return the index/key of object
so if you are trying to get value of each key try.
for( var prop in srcObj )
{
console.log(srcObj[prop]);
}
if you are trying to get each key name then try this one
for( var prop in srcObj )
{
console.log(prop);
}
All you need to do
for (var prop in srcObj) {
console.log(srcObj[prop]);
console.log(srcObj[prop]["risklevel"]); // --> Medium
var keyNames = Object.keys(srcObj[prop]); // --> return keyNames as array
console.log(keyNames[0], keyNames[1]); // --> location piidata
}
Your srcObj is an array. You can tell by the square brackets [] it's enclosed in. But Chrome says Object. Right. Javascript types are a little strange. Check out this page.
If you want to access the key/values in the object, you can specify the index of the object within the array. srcObj[0] in this case. If you want to get the object out of the array and deal with it just as an object, you can do something like this:
var trueObject = srcObj.shift()
Which removes and returns the first element of an array and assigns it to your variable.
Your srcObj is actually an array (identified by the [ and ] literals) which contains an object as its only element.
To access the parameters of the single object inside the array, use the following syntax:
for( var prop in srcObj[0] )
{
console.log(prop);
}
jsFiddle Demo
What is the best structure solution for find element(Object) in Object Array by value of one of the keys.
For example we have array:
var someArray =
[
{id:17, color:'black', width:50},
{id:34, color:'red', width:150},
{id:49, color:'gree', width:10}
]
and we need to find an Object with id-key = 34.
And each time we will have to do the loop to find the object.
I thought about restructuring and having object instead of array like so:
var someObject =
{
17: {id:17, color:'black', width:50},
34: {id:34, color:'red', width:150},
49: {id:49, color:'gree', width:10}
}
Now we can do it in one step someObject[34], BUT what if we want to keep the order?
Thanks in advance.
I thought about restructuring and having object instead of array
Yes, that's fine.
BUT what if we want to keep the order?
I tend to use an extra array that contains the keys in the correct order, like
var order = [17, 34, 47];
To loop them, you'd use
for (var i=0; i<order.length; i++) {
… someObject[order[i]] …
}
You should prefix the id to avoid naming collisions, like this:
var database =
{
'row_17' : {id:17, color:'black', width:50},
'row_34' : {id:34, color:'red', width:150},
'row_49' : {id:49, color:'gree', width:10}
};
At this point you can query the object with this code:
function retrieve(database, id)
{
id = 'row_' + id;
if (!database.hasOwnProperty(id))
{
return null;
}
return database[id];
}
The persist function would be:
function persist(database, obj)
{
database['row_' + obj['id']] = obj;
}
If you need to keep an order you have first to understand what order you are talking about.
Of the id? Of the insert? Or of an arbitrary property?
There are solutions to all of these by filtering (extracting the items and putting them into a separate array that would be the query result or with additional fields or structures.
EDIT: how to keep insertion order
You'll need an array that keeps track of order:
database._ordered = [];
On insert, push the item there, too:
database._ordered.push(obj);
Now you can pick single items by key and all items ordered.
There is no way you can have an order in an object, it's simply the wrong tool for that.
The row_ prefix is recommended to avoid naming collisions with methods and whatnot. An object should hold properties and methods, if you use it like a dictionary at least prevent interference by prefixing.
You can use function findWhere from underscore library, in your case it would be like this:
_.findWhere(someArray, {id: 34})
it's frustrating that we can't select JSON elements (or really any elements) using a similar code like this:
//An JSON object is parsed into Response beforehand
for(var count = 1; count <= Response.objCount; count ++) {
console.log(Response.obj+count.content);
}
In the code, I want to output a JSON object like this:
{ "objCount" : 2 ,
"obj1" : { "result" : true ,
"content" : "blah blah 1" } ,
"obj2" : { "result" : true ,
"content" : "blah blah 2" } }
But no, we can't use variable as whole or part of an identifier in Javascript..
So, any suggestions on how to handle such JSON objects when I want to output each and every object?
Thank you!
If "Response" is your structure, then you can indeed do what you ask:
for(var key in Response) {
console.log(Response[key].content);
}
You can't loop on "length" because "Response" is not an array, and plain objects don't have a "length" property.
Now, one problem is that you can't be sure that you'll get the components out in any particular order. That is, the loop above may give you "obj2" before you get "obj1". You could address that problem in a couple of ways. First, you could re-think your data structure and store it as an array. Alternatively, you could fetch the keys and sort them, and then iterate through the sorted array of property names.
var keys = Object.keys(Response);
keys.sort(function(key1, key2) {
// comparison ...
});
for (var count = 0; count < keys.length; ++count)
console.log(Response[keys[count]].content);
The Object.keys() function only works in newer browsers, but you can do a similar trick with a for ... in loop to pull out the property names.
edit — with your updated structure that includes an explicit property of your own for the length, you can use a plain for loop:
for (var count = 1; count <= Response.objCount; ++count)
console.log(Response["obj" + count].content);
Use brackets to access the property using the property name as a string:
Response["obj" + count].content
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example