cant seem to loop through object keys - javascript

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

Related

I am trying to add an element to a js object

I try to push key value pairs to an object. the key value pairs have to be added to a certain index which is given by the e.vatRecord.debit. This variable is working properly if I log this on console. But in combination it does not work.
journalByAccounts = {}; // define an object
data.entries.forEach(function(e) {
journalByAccounts[e.vatRecord.debit].push({
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
});
});
Either you first need to initialize the object journalByAccounts[e.vatRecord.debit] to an empty array [] because you can't push into undefined (expecting that it magically becomes an array):
journalByAccounts = {};
data.entries.forEach(function(e) {
if (!journalByAccounts[e.vatRecord.debit])
journalByAccounts[e.vatRecord.debit] = [];
journalByAccounts[e.vatRecord.debit].push({
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
});
});
The if is being done to make sure that it still goes right if e.vatRecord.debit can contain the same value more than once, creating the array only once for each value.
Or if you don't actually want an array, then you should do an assignment:
journalByAccounts[e.vatRecord.debit] = {
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
};
journalByAccounts = []; // define an object
you must define an empty array, not an obj.

Count the recurrence of a word

I am writing a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
function countWords(str) {
var obj = {};
var split = str.split(" ");
return split;
}
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> MUST RETURN {ask: 1, a: 2, bunch: 2, get: 1}
Have any idea?
I wont give you finished code ( thats not the sense of a homework) , but i try to get you to solve the problem on your own.
So far you've already got an array of words.
Next lets declare an object we can assign the properties later.
Then we'll iterate over our array and if the array element doesnt exist in our object as key yet ( if(!obj[array[i]])) well create a new property, with elements name and the value 1.( obj[array[i]=1; )
If the element is a key of that object, lets increase its value.
( obj[array[i]]++;)
Then return the object.
So you could use a javascript Map for this like so:
var myMap = new Map();
myMap.set(keyString, count);
and access the value of the key like so:
myMap.get(keyString);
For more information you can read up here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

How to access multidimensional array by index in javascript?

I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/

Adding to JSON array in JavaScript/jQuery

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

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Categories