Accessing dynamic values from JSON object in javascript - javascript

this is my json object. i need to get only all the values of packageName and assign it to an array. can any body help me with that. i can not go for using indexes since this is dynamic object.
thanks in advance.
var data = [
{
"packageName":"string",
"packageValue":"string"
},
{
"packageName":"string",
"packageValue":"string"
}
]

Use javascript map function
var packageNames = data.map(function(obj){
return obj.packageName;
})
var data=[
{
"packageName":"string1",
"packageValue":"string"
},
{
"packageName":"string2",
"packageValue":"string"
}
]
var packageNames = data.map(function(obj){
return obj.packageName;
})
console.log(packageNames)

You can use filter function and add to array only when this key exists.
var arr = [];
data.filter(getValue)
function getValue(data){
if(data[packageName]){
arr.push(data[packageName])
}
}

You can add an if statement to check the key and then push it to an array.
for(var i = 0; i< data.length; i++){
for (var property in data[i]) {
if (data[i].hasOwnProperty(property)) {
console.log(property);
console.log(data[i][property]);
}
}
}

Related

javascript update or add values to array

I want to add values to array. But the same values may update. for example my array is
[{"abc1":"123456"},{"abc2":"123456"}]
when is adding again is abc1. It may update. For example in normal case
[{"abc1":"123456"},{"abc2":"123456"},{"abc1":"123456"}]
But i want
[{"abc2":"123456"},{"abc1":"123456"}]
My code
var categories = [],
arrIndex = {};
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
var index = arrIndex[object[0]];
console.log("index:"+object[0]);
if(index === undefined) {
index = categories.length;
}
arrIndex[object[1]] = index;
categories[index] = object;
}
console.log(categories);
It not showing correct answer.
It shows
[{"abc3":"129"}]
I want
[{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}]
How it possible? Please help me?
You could use Array#findIndex ans plice the object from categories if the index is found, then push the new object to categories.
function addOrReplace(object) {
var key = Object.keys(object)[0],
index = categories.findIndex(o => key in o);
if (index !== -1) {
categories.splice(index, 1);
}
categories.push(object)
}
var categories = [];
addOrReplace({ abc1: "125"});
console.log(categories);
addOrReplace({ abc2: "126"});
console.log(categories);
addOrReplace({ abc1: "127"});
console.log(categories);
addOrReplace({ abc3: "129"});
console.log(categories);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var categories = new Map();
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
for (var name in object)
categories[name] = object;
}
console.log(categories);
var categories = [],
arrIndex = {};
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
for(var c in categories){
if(Object.keys(categories[c])[0] == Object.keys(object)[0]){
categories.splice(c,1)
}
}
categories.push(object)
}
console.log(categories);
//[{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}]
I don't know how you would be finally using the final data but in case you are looking for the uniqueness, i would like to recommend to go for object hash instead of array.
Initially :
{
"abc1" : "123456",
"abc2" : "123456"
}
If you now add { "abc1" : "some_other_value" }.
{
"abc1" : "some_other_value",
"abc2" : "123456"
}
You can also check if the value exist already or not using if(objectHash('abc1')).
It can save you from extra traversal and would overwrite values if already present.

Get JSON stringify value

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

Access to a certain part of JSON data with jQuery

So i have this JSON:
{
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
}
I just want to access to the fields names
id_u,_nombre_usuario,apellido_paterno_usuario
And then, create an array with that info.
How can i do that?
Thanks guys
Do this way :
var keyValuePair = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
var arr =new Array();
for (key in keyValuePair){
arr.push(key); // for keys
// arr.push(keyValuePair[key]); // for values
}
Use .each() to parse JSON.
Try this:
var keyArray = [];
var a = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
$.each(a,function(i,v){
keyArray.push(i); // i is json key and v is json value.
});
console.log(keyArray);
DEMO
Object.keys(jsonObject) is enough.

how to get length of json encoded array in javascript?

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.
You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));
For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}
var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

Get value from json object without count the array number

This is my json object i want to get alert it without the array order like[0], [1].
var jsononj = {
"objnew" :
[{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] };
}
var newtest = jsononj.objnew[0].testarry;
alert(newtest);
i want to alert without [0]. how to i achieve this
I think this is what you're looking for:
var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
if (jsonobj.objnew[i].testarry) {
alert(jsonobj.objnew[i].testarry);
}
}
This is just stupid but I removed the [0]
var jsononj = {
"objnew" : [
{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
]
};
var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);
That's not JSON, that's a Javascript object. JSON is a text format for representing data.
If you want to look for an object with a specific property, loop through the objects in the array and check for it:
var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
var obj = jsononj.objnew[i];
if (obj.hasOwnProperty('testarry') {
newtest = obj.testarry;
break;
}
}
if (newtest != null) {
// found one
}
doing a var firstOne = jsononj.objnew[0];
but if you simply don't like the [0] through your lines, extend the Array prototype
Array.prototype.first = function () {
return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);
more info at First element in array - jQuery

Categories

Resources