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/
Related
Below is the code snippet.
Expected : The output of the alert must be:
210 then 202 then 201
Working currently :
201 then 202 and 210.
Issue is, I want in insertion order and not in sorted order.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var newItem = new Array();
newItem['210'] = new Array(1,'test1');
newItem['202'] = new Array(2,'test1');
newItem['201'] = new Array(3,'test1');
for(var item in newItem) {
alert(item);
}
</script>
</body>
</html>
If you want to go with insertion order, and strings as keys, use a Map.
From the documentation
A Map object iterates its elements in insertion order — a for...of
loop returns an array of [key, value] for each iteration.
let newItem = new Map();
newItem.set('210', [1,'test1']);
newItem.set('202', [2,'test1']);
newItem.set('201', [3,'test1']);
for ( let item of newItem ) console.log(item);
A couple things - arrays have one value per index slot, like this:
[1,2,3,4]
What you're creating above is a key/value pair, which in JavaScript is an object - object keys have no sort order - so getting them in the order they were inserted just isn't going to happen. What you want is an array of objects
var arr = [];
var obj = { '201' : [1, 'test1'] }
//create the rest of your objects
arr.push(obj);
And another note, when you iterate an array, you use the regular for syntax - when you iterate an object, use for..in
for (var i = 0; i < arr.length; i++) {
var objKeys = Object.keys(arr[i]); //get the keys of the object being iterated over
console.log(objKeys[0]); //log the first key (since your objects only have 1 key
}
Use can set the key, that is "210", "202", "201" as the first element of the created array for each key; use Array.of() to set created arrays as element; iterate array created with Array.of() at for..of loop. Optionally utilize Array.prototype.entries() chained to created array to confirm index of created array containing key as first element within array.
let items = Array.of(["210", 1, "test1"]
, ["202", 2, "test1"]
, ["201", 3, "test1"]);
for (let [key, value] of items.entries()) {
// do stuff
console.log(key, value)
};
Below a very simple code example for what you are trying to achieve, based on your question's expected output.
var newItem = [];
newItem.push('210');
newItem.push('202');
newItem.push('201');
newItem.forEach( value => console.log(value) )
Is this needed in JavaScript in any context? For example I am trying to copy an array and for some reason when I loop through it and copy the values over one by one the resulting array is missing one value; the only thing I can think of why this is so is because the array I am looping over isn't starting at the beginning.
So, is there a way to reset the internal pointer of an array in JavaScript?
Try:
var myArray = ["aa", "bb"];
var myArray2 = [];
for (var i=0, tot=myArray.length; i < tot; i++) {
myArray2.push(myArray[i]);
}
I understand the basic structure of a For loop in JavaScript. I was looking at the following example:
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
On the Fourth line I don't understand what you would call the
[i] in terminology and why it is square brackets?
[] is a way of selecting a property from an object given a specific key, in this case the key (or index) is i and the object is an array. In an array an index can go from 0 to the length of the array - 1.
In an object a key is the name of any property within that object. For example, you can also select the value of the property key selected from the object selectObject.options[i] by using the following: selectedObject.options[i]['selected'].
As an alternative to your for loop, you could use a for in loop. Which works on objects (and arrays).
for (var key in selectObject.options) {
if (selectObject.options[key].selected) {
numberSelected++;
}
}
the [i] is used to address variables in for example an array.
Lets say you have an array names containing sarah and john. names[0] would return sarah.
What your for loop does is go over all the entries in selectObject.options and looks at the value of selected (most likely a true/false).
selectObject.options returns an array, and the [ ], is the way to get an element from the array, using its index (the i in your case)
Say you had an array of strings like so:
var arr = ["this", "is", "an", "array", "of", "strings"];
and you want to access one of the array's elements, you would:
console.log(arr[5]); // prints "strings" to the console
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
In this above code why is numberSelected, and in the coditional statement numberSelected++
I am storing a json object in json array and assign it to another main json object, but when I print the value of main json object it display 1. Below is the code.
var jsonMainObject= {};
var jsonArray= [];
for(var j=0;j<cu.receivedData.length;j++) {
jsonMainObject["company"] = jsonArray.push(cu.receivedData[j].company);
}
console.log(jsonMainObject)
Below is the output
{ company: 1 }
But it should show the array. when i print jsonArray it shows the array of object, but when I console the output of jsonMainObject it displays the above output.
The push method returns the new length of the array. See documentation. I guess you should use:
jsonMainObject["company"].push(valueToPush)
or use concat (documentation)
jsonMainObject["company"] = jsonMainObject["company"].concat(valueToConcat)
There is no JSON at all here. JSON is a text format for representing data. What you have is a JavaScript object with a JavaScript array.
You are trying to put the array in the object at the same time as putting items in the array. The push method doesn't return the array that it was called on, it returns the length of the array. The company property will end up containing the length of the receivedData array.
You can put the array in the object from start:
var arr = [];
var mainObject = { company: arr };
for(var j = 0; j < cu.receivedData.length; j++) {
arr.push(cu.receivedData[j].company);
}
console.log(mainObject);
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