jQuery taking value from object - javascript

I have an object, I want to take a value, for example "title1", what function should I use to solve the problem.
please help me.
[{
total1 : "1200",
total2 : "800",
title1 : "Birth Rate",
title2 : "Death Rate",
year : "2011"
}]
sorry for my mistake..that data is the result from console.log()
The data derived from
$( ".residentgraph" ).each(function(i,el) {
var ids = $(this).attr('id');
var value = $('#'+ids).val();
var dataVal = value.split("/");
chartData.push({
'title1' : dataVal[0],
'title2' : dataVal[1],
'total1' : dataVal[2],
'total2' : dataVal[3],
'year' : dataVal[4]
});
});

I assume that you are having this array in a variable called xArr,
console.log(xArr[0].title1);
DEMO

Related

Extract fields from Json based on a list in Javascript [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
I'm trying to extract some of the fields from a Json response and push them into a Javascript array. I want the selection of the fields to be configurable. Here is what I'm doing:
Consider this as my JSON string:
{
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
}
Say I want to extract some of the fields (defined in the FIELDS variable) and push them in an array.
# NOTE: the variable `data` here is my json object
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
var lineItem = []
# parse the data (my Json object)
for (var i = 0; i < FIELDS.length; i++){
lineItem.push(data[FIELDS[i]])
}
So, this seems to be working OK for the first level (the id, orderNumber and customerEmail) but not for the billingAddress.firstname, etc. This is what I'm wondering about.
My intent is to be able to modify the definition in the FIELDS variable without needing to make any change to the logic in the code.
Hope this makes sense.
Thanks!
As long as there are no periods in the key names this will work.
var data = {
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
};
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName'];
var lineItem = [];
for (var i = 0; i < FIELDS.length; i++){
let obj = data;
let parts = FIELDS[i].split(".");
while(parts.length) obj = obj[parts.shift()];
lineItem.push(obj)
}
console.log(lineItem);
You just need a function that will split that path on . and traverse the JSON data. With that you can just map() over your fields.
let data = {"id" : "1234","orderNumber" : "1196","createdOn" : "2019-07-02T12:03:39.697Z","modifiedOn" : "2019-07-02T12:25:52.126Z","testmode" : false,"customerEmail" : "a#b.com","billingAddress" : {"firstName" : "John","lastName" : "Doe","address1" : "Wall Street","address2" : null,"city" : "NYC","state" : "NY","countryCode" : "US","postalCode" : "12345","phone" : "1122334455"}}
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
// split an traverse
const getFromPath = (path, data) => path.split('.')
.reduce((curr, p) => curr && curr[p], data) // check for curr incase path is undefined
console.log(FIELDS.map(p => getFromPath(p, data)))
The function getFromPath will return undefined if any part of the traversal is not found in the object.

Fetching records from inside a JSON Object inside an Array

I have an API response coming in this format.
[{
"response_data": {
"0":{
"id" : 0,
"office" : "India",
"type" : 'Perm'
},
"1":{
id : 0,
"office" : "America",
"type" : 'Perm'
},
"2":{
id : 0,
"office" : "Europe",
"type" : 'Contract'
},
"2":{
id : 0,
"office" : "Latin America",
"type" : 'Contract'
}
}}]
I am trying to get all the office where the type is Contract. I have the json response saved in a variable like - using Chakram as
var response_json = t.body[0].response_data;
which gives me correct response in the console.log as
"0":{
"id" : 0,
"office" : "India",
"type" : 'Perm'
},
"1":{
id : 0,
"office" : "America",
"type" : 'Perm'
},
"2":{
id : 0,
"office" : "Europe",
"type" : 'Contract'
},
"2":{
id : 0,
"office" : "Latin America",
"type" : 'Contract'
}
Now how to get to the corresponding keys in inside the json and extract the information required. I tried this but it returns undefined
var length = Object.keys(response_json).length;
for(var i = 0; i<= length;i++){
console.log(response_json.i) //returns undefined
console.log((Object.keys(response_json)).id); //returns undefined.
}
I know that this can be solved using filter method if the response was an array, but how can I do the same operation in JSON object? I am looking for an optimized solution because the API returns almost 5000 objects.
If this question has already been asked, provide reference since I was not able to find any on SO.
If you want to do this with filter method then
a workaround would be to add a property length then using Array.from like below. Then you can use Array.prototype.filter method.
let o = {
'0': {
id: 0,
"office": "India",
"type": 'Perm'
},
'1': {
id: 0,
"office": "America",
"type": 'Perm'
},
'2': {
id: 0,
"office": "Europe",
"type": 'Contract'
}
};
o.length = Object.keys(o).length;
let a = Array.from(o);
let r = a.filter(({ type }) => type == 'Contract');
console.log(r);
Two major mistakes your code have one using loop up to the length of an array where index starts from 0. and second accessing an object from an array you use brackets instead of the dot. So update the code as follows:
var keys = Object.keys(response_json);
var length = keys .length;
for(var i = 0; i< length;i++){
console.log(response_json[keys[i]]);
}
On your response_json '0' , '1' all keys are in string format.
But in your for loop 'i' is integer so key is unavailable. just convert it to string you can get desired result
like console.log(response_json[''+i])
var data = [{"response_data": {
'0':{id : 0, "office" : "India", "type" : 'Perm'},
'1':{id : 0, "office" : "America","type" : 'Perm'},
'2':{ id : 0, "office" : "Europe","type" : 'Contract'},
'3':{ id : 0, "office" : "Latin America", "type" : 'Contract'}
}}];
var list = data[0]['response_data'];
var filterList = [];
for(var i in list) {
if(list.hasOwnProperty(i)) {
var type = list[i]['type'];
if(type === 'Contract') {
filterList.push(list[i]);
}
}
}
May be not better in javascript if the record is more than 5 thousand, better process it on server side.

Convert arrays to key value pair

I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}
You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));
You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework

building an array object by pushing json

I have two objects as follows:
var id="one";
var arrobj = Array[2]
0: Object
name : "a"
desc : "desc1"
1: Object
name : "b"
desc : "desc2"
I am trying to build the object in the following format :
var secondobj = [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]
I tried this :
var secondobj= new Array();
var samplejson = {};
I just gave
samplejson.name = id;
After this I am a bit confused as in how to push values to get the above data structure.
It is a simple as:
samplejson[id]=arrobj;
var arrobj = [{
"name" : "a",
"desc" : "desc1"
},{
"name" : "b",
"desc" : "desc2"
}]
var secondobj = [];
secondobj.push({
one : arrobj
})
console.log(secondobj);
Check this jsfiddle for demo
To make the above structure you can try this:
var secondobj= new Array();
var samplejson = {};
samplejson.one = arrobj;
secondobj.push(samplejson);
console.log(secondobj) // this will give [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]

Ordering JSON Objects using jQuery

I have the following JSON Object being loaded into my application and stored into a var called obj:
{
"items" : [
{
"name" : "item-1",
"group" : [
{
"groupName" : "name-1",
"groupPosition" : 2
},
{
"groupName" : "name-2",
"groupPosition" : 1
}]
},
{
"name" : "item-2",
"group" : [
{
"groupName" : "name-1",
"groupPosition" : 1
},
{
"groupName" : "name-2",
"groupPosition" : 2
}]
}]
}
I then do the following to go through it:
var groups = new Array();
var items = new Array();
$.each(obj.items, function(i,r){
var itemName = r.name;
$.each(r.group, function(index, record){
if ($.inArray(record.groupName) == -1) {
groups.push(record.groupName);
$('body').append('<div id="record.groupName"></div>');
}
$('#'+record.groupName).append('<div id="itemName">itemName</div>');
// At this point I'm stuck as the items get added in order of iteration,
// not according to their record.groupPosition value.
});
});
There will eventually be several hundred "items" each contained within an unset number of "groups".
The trouble I'm having is how to iterate through the JSON object using jQuery or good ol'JavaScript and display the items in the correct position within each group as the items and groups won't be listed inside the JSON object in sequential order.
Any help would be greatly appreciated!
Thank you.
Why not just give the group items the position index like this:
{
"items" : [
{
"name" : "item-1",
"group" : {
2:{
"groupName" : "name-1",
"groupPosition" : 2
},
1:{
"groupName" : "name-2",
"groupPosition" : 1
}}
},
{
"name" : "item-2",
"group" : {
1:{
"groupName" : "name-1",
"groupPosition" : 1
},
2:{
"groupName" : "name-2",
"groupPosition" : 2
}}
}]
}
Assuming you have a variable which is assigned to this:
var data = ...
you could use the $.each() method:
$.each(data.items, function(index, item) {
// here item.name will contain the name
// and if you wanted to fetch the groups you could loop through them as well:
$.each(item.group, function(i, group) {
// here you can use group.groupName and group.groupPosition
});
});
Arrays ([]) in javascript are 0 index based and preserve their order when you are iterating over them.
If I understood correctly your problem it is not about the sorting it self but how to link them to your dom nodes, solution: use classes with numbers.
For example:
$(".group"+items[1].group[0].grouposition").append(items[1].group[0].name);
// this will give append to the element with class="group1"
If you join this with having the html structure that is being generated to match the same names, then it won't be a problem and you don't have to sort them

Categories