How to access element in JSON and Javascript - javascript

How do I access something like this with Javascript and Jquery?
"condition" : [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]
(this is just an excerpt)
I tried using item.condition and I got:
[{"conditionId":["3000"],"conditionDisplayName":["Used"]}] as a result.
How do I get the conditionDisplayName?
I've also tried using : item.condition.conditionDisplayName but it doesn't work nor does item.condition[1]

You're almost there but your condition is an array with one object so you need to use the array notation to access it:
var displayName = item.condition[0].conditionDisplayName;
If there could be more than one object in the array, you can use a loop:
for(var i=0; i<item.condition.length; i++) {
console.log( item.condition[i].conditionDisplayName );
}

condition is an array, as is conditionDisplayName, so you will need to access their members using an index. For example, to get the first displayName of the first condition you would do:
var displayName = item.condition[0].conditionDisplayName[0]

You can use array index to get the object
var displayName = obj.condition[0].conditionDisplayName;

In your case you should try:
item.condition[0].conditionDisplayName

var array = [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]
// Not right - show ["Used"]
console.log(array[0].conditionDisplayName);
// Right - show "Used"
console.log(array[0].conditionDisplayName[0]);
You can see this here: http://jsfiddle.net/bs9kx/

Related

How to get item from JSON object when there is only one item?

I have the following JSON:
var x = [{"email":"info#test.nl"}]
How do I get the email in javascript? x.email doesn't work for me.
Bart
You need to reference to element of the array, then access the property.
var x = [{"email":"info#test.nl"}]
console.log(x[0].email)
Since the object is inside of an array, you must access the correct array element first, so use: x[0].email
if you want to read the JSON inside an array, use x[0].email.
You need to parse the JSON first:
var arr = JSON.parse(x);
var entry = arr[0].email;

javascript how to add new object into object after it has been created

This is my object:
var example = {"119":{"bannerId":"119","overlay":"3","type":"1",...},"210":{"bannerId":"210","overlay":"3","type":"1",...},...}
In this way I can very easily access or modify object. For example if I want to add new property I simply call this:
example[119].newProperty = 1;
And very easily access it:
alert(example[119].newProperty)
alert(example[210].type)
By knowing banner id, I can access any data from any scope of code, this is the reason I chose this pattern. The problem is that I need to add new object inside example after it has been created. For example I need to push this into example:
{"30":{"bannerId":"119","overlay":"3","type":"1",...}}
And I don't know if this is possible. Is it? One way to solve this problem would be to use array, so example would be array and each key would carry object, and I could push into array new key with object. But I am not sure if this is proper way because key will start with 200, 300, ... console.log(example) shows undefined for all keys before 200. Is fine to have so many empty keys? Is any other better way?
EDIT:
I realized this can be done also with object. The problem was because I was trying to assign new property directly into new object like this:
example[200].example3 = 2;
guessing it is enough that example object is created. What I was missing is this line:
example[200] = {}
Thanks for answers, it works now!
var example = {};
example["30"] = {"bannerId":"119","overlay":"3","type":"1"}
console.log(example);
If its inside a loop you can also try something like below.
var i = 0;
var example = {};
for (i=0; i<10; i++) {
example[i] = {bannerId : i+1 , someOtherItem : i + "Hello"}
}
console.log(example);
example[30] = {"bannerId":"119","overlay":"3","type":"1",...};
You can always access (and assign) ad hoc keys of objects, even if you didn't define them in the first place.
So for your example you can just do:
example["30"] = {... /*your new object*/...}
It seems that you want to extend your object, you could use jQuery or underscore more or less like this:
$.extend(true, example, { "30": { objectId: "201" }}); // deep copy
If you don't want to use any library simply do:
example["30"] = myObj["30"];

How to get the last element of a json file with jquery

$.getJSON('./file-read?filename='+filename+'&parameter='+parameter, function(data) {
var firstElement = data[0][0];
var lastElement = ?
});
I try to find out the last Element in my JSON file.
My JSON File looks like this:
[[1392418800000,6.9],[1392419400000,7],[1392420000000,7.1],[1392420600000,7.2],[1392421200000,7.2]]
can anybody help me to read extract the last date(1392421200000) ?
Just pick the (length - 1)th element with this:
var lastElement = data[data.length-1][0];
Another way is to use array methods, e.g. pop which will return the last element of the array:
var lastElement = data.pop()[0];
N.B.: The first approach is the fastest way of picking the last element, however the second approach will implicitly remove the last element from data array. So if you plan to use the initial array later in your code, be sure to use either the first method or alternative solution provided by #matewka.
VisioN's answer is nice and easy. Here's another approach:
var lastElement = data.slice(-1)[0];
// output: [1392421200000,7.2]
Negative number in the slice method makes the slice count from the end of the array. I find this method more compact and simpler but the disadvantage is that it returns a smaller, 1-element array instead of the element you wanted to fetch. If you want to fetch only the timestamp you'd have to add another [0] to the end of the expression, like this:
var lastElement = data.slice(-1)[0][0];
// output: 1392421200000
You can use :
var data = " any json data";
var lastelement = data[ Object.keys(obj).sort().pop() ];
Object.keys (ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.

How can I store values from one array to another array using 'for' loop

I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg

Can I access directly to the second value of an array after .split()?

I have this code :
var tmp=$(this).attr('id').split("_");
and I'd like to store on tmp the second value after the split. So if $(this).attr('id') = "hello_marco" I'd like to store in tmp the value marco, not the array.
Of course, I want to do it directly in one line of code, without first store the array and the access to it with array[1].
Is it possible on JS/Jquery?
var tmp = $(this).attr('id').split("_")[1];
var tmp = $(this).attr('id').split('_')[1];
// ^^^
Split returns an array, so just dereference the array.
Just add it to the end
var tmp=$(this).attr('id').split("_")[1];
it's not probably best practice but it works
var tmp = $(this).attr('id').split("_")[1];

Categories

Resources