Returning number of elements of JSON object - javascript

I need to iterate over every element in a JSON object, and I'm having trouble working out a way to count the number of elements in that object so I can use a for loop to iterate. Here's my object:
this.worldData =[
{"0":{"1":"0", "2":"0"},
"1":{"1":"0", "2":"0"},
"2":{"1":"0", "2":"0"}}
];
And what I'm trying:
alert(this.worldData.length);
Problem is, it always returns 1, no matter how many elements I put into the JSON object.

Do you have control over the JSON data? The length is returning 1 because there is only one element in the array. This is because of the way the JSON data is structured here. If you want something easier to iterate over, you would want something like this:
this.worldData = [
{"1":"0","2":"0"},
{"1":"0","2":"0"},
{"1":"0","2":"0"}
]
Note that objects (denoted with {}) don't have a length property, while arrays (denoted with []) do.

You're wrapping all of your objects inside a single object (the first and last curly braces). Try this:
this.worldData =[
{"0":{"1":"0", "2":"0"}},
{"1":{"1":"0", "2":"0"}},
{"2":{"1":"0", "2":"0"}}
];
jsFiddle example.

Related

Javscript: remove curly brackets from objects(with keys and values) in an array

I have an array like this(data retrieved from mySql and json_encode() in PHP, coming back as a json object(totally 19 elements in this array, and all the objects in different order in the element)):
const array=[
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]
How to convert it to an array like this, removing curly brackets?
const array=[
{"name":"jason","age":16,"location":"London"},
{"name":"amy","age":24,"location":"Tokyo"}
]
I have tried to convert to string, then
String.replace(/[{}]/g, '');
But what's next? I got stuck at converting back to array again.
And the other question is:For an array like this, when to access the keys and values, is it neccesary to re-structure the keys and values to make them the same order in each element, otherwise it doesn't look nice and is not easy to access?
[
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]
Any tips on how to think about flattening this will be much appreciated!
The .replace() method is used for strings, not objects/arrays. Instead, you can merge the objects within each inner array together by using .map() to trasform each array, and Object.assign() to merge the given array of objects.
See example below:
const array = [
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
];
const res = array.map(inner => Object.assign({}, ...inner));
console.log(res);
The order of your (string) keys in the resulting objects will appear in the order that they're inserted, so as your object order is different for each inner array, your resulting object's key-ordering will also be different once they're merged. However, this shouldn't matter too much as relying on object key ordering is often not the best idea, and can be done more reliably using other methods.

Javascript get value from an object inside an array

I have an object with key value pairs inside an array:
var data = [
{
"errorCode":100,
"message":{},
"name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"value":"2"
}
];
I want to get the value of "value" key in the object. ie, the output should be "2".
I tried this:
console.log(data[value]);
console.log(data.value);
Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.
You can use the map property of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.
data.map(x => x.value)
You are trying to get the value from the first element of the array. ie, data[0]. This will work:
console.log(data[0].value);
If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.
data.map(x => console.log(x.value));
data.forEach(x => console.log(x.value));
data is Array you need get first element in Array and then get Value property from Object,
var data = [{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}];
console.log(data[0].Value);
Try this...
Actually Here Data is an array of object so you first need to access that object and then you can access Value of that object.
var data = [
{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}
];
alert(data[0].Value);
what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like
data[0] and then read a property of the fetched object, i.e. .value,
so the complete syntax would be data[0].value
Hope it helps !

How to find index of object in array without iterating in javascript

Lets have an sample array like [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ]
I want to find the first occurrence of ' 0 ' in this array, but without iterating the same.
all the functions 'like', 'map', 'grep', 'filter', 'some','for each' everything iterating every element in the array to find the same. Considering big data array's its very much bottleneck considering performance.
I have tried all the above methods.
Anybody has any idea about this?. Thanks for your time.
How to find index of object in array without iterating in javascript
This is impossible. If you have a generic list of values, you have to look at each element until you find the one you are looking for.
If you want O(1) access then you need to use a different data structure.
If the elements of the array is a number or string, you can just use indexOf()
indexOf() compares searchElement (first parameter) to elements of the Array using strict
equality (the same method used by the ===, or triple-equals,
operator).
var list = [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ];
var firstOccurence = list.indexOf(0);

Using index to pull items from an object

If I have an object with items named and ending in sequential numbers:
var theobject = { item1:, item2:, item3:, ...etc }
this method of extracting the objects and used in a for loop does not seem to work. Should this work provided the rest of the function is correct?
theobject.item+i
You can do something like theobject['item'+i].
But you can do something better using jquery foreach so that you can iterate over keys.

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories