i have a fiddle here http://jsfiddle.net/prantikv/eqqd6xfm/3/
i have data as such
var info={
"company1":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company2":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company3":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
]
i get the data from an a json file.
what i want to do is that i want to create individial company variables so that i can load them up quickly without other company data
so what i do is this
var companiesArray=[];
for(company in info){
console.log("company--> "+company);//company1,2,etc
var detailsArray=[];
for(var i=0;i<info[company].length;i++)
{
//loop through the inner array which has the detials
for(var details in info[company][i]){
var detailsValue=info[company][i][details];
detailsArray[details]=detailsValue;
}
}
companiesArray[company]=[company,detailsArray];
}
console.log(companiesArray);
so when i try to get the data i have to do something like this
companiesArray['company1'][1].employee
what i want to do is this
companiesArray['company1'].employee
where am i going wrong?
If You don't want to /cannot change the JSON, simply change
detailsArray = []
to
detailsObject = {}
and
companiesArray[company]=[company,detailsArray];
to
companiesArray[company]=detailsObject;
Now you can use
companiesArray['company1'].employee
You have to form your json like this:
var info={
"company1": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
},
"company2": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
},
"company3": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
}
};
Use curly braces ({}) instead of brackets ([]) in order to create objects accessible with the dot notation like this:
info.company1.employee
I agree with #Pavel Gatnar and #Guillaume. This is a very bad data structure. If you can't change the structure only then should you use the following code.
var info = {
"company1": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}],
"company2": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}],
"company3": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}]
};
var companies = {},
companyNames = Object.keys(info);
companyNames.forEach(function (companyName) {
var companyInfo = info[companyName],
company = {};
companyInfo.forEach(function (properties) {
var innerPropertyName = Object.keys(properties);
innerPropertyName.forEach(function (property) {
company[property] = properties[property];
});
});
companies[companyName] = company;
});
console.log(companies);
check out the fiddle here
Try this:
var info={
"company1":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company2":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company3":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
]
};
var companiesArray = {};
for(company in info){
var detailsArray = {};
for(var i=0;i<info[company].length;i++) {
for(var details in info[company][i]){
var detailsValue=info[company][i][details];
detailsArray[details]=detailsValue;
}
}
companiesArray[company]=detailsArray;
}
console.log(companiesArray['company1'].employee);
Related
I'm using JSEL (https://github.com/dragonworx/jsel) for search data in a huge JSON. This is an extract:
{
"Clothes":[{
"id":"clothes",
"items":[{
"shoes":[{
"sizes":{
"S":{
"cod":"S1"
},
"M":{
"cod":"M1"
},
"L":{
"cod":"L1"
}
}
}],
"pants":[{
"sizes":{
"S":{
"cod":"PS1"
},
"M":{
"cod":"PM1"
},
"L":{
"cod":"L1"
}
}
}]
}]
}]
}
If I execute this command:
var dom = jsel(data);
console.log( dom.selectAll('//#cod') );
I obtain an array with all "cod" key values from JSON:
['S1', 'M1', 'L1', 'PS1', 'PM1', 'L1']
I'm newbie on XPath expressions and I want to get the parent keys of a certain "cod" key value, for example, if "cod" key value is "S1" the result is:
"shoes"
or
"items"
or
"Clothes"
How can I get it? I'd like to receive your help
There are lot of ways available in JS. I usually prefer this kind it's more quick and reusable in any kind of objects.
You can try below snippet and you will get it more clear.
var jsonString = '{"Clothes":[{"id":"clothes", "items":[{"shoes":[{"sizes":{"S":{"cod":"S1"}, "M":{"cod":"M1"}, "L":{"cod":"L1"} } }], "pants":[{"sizes":{"S":{"cod":"PS1"}, "M":{"cod":"PM1"}, "L":{"cod":"L1"} } }] }] }] }';
const myObj = JSON.parse(jsonString);
for (let i in myObj.Clothes) {
var clothes = myObj.Clothes[i];
var clothesId = clothes.id;
var clothesItems = clothes.items;
console.log(clothesId);
var products = Object.keys(clothesItems[0])
for( var productName in products ){
var productName = products[productName];
var productSizes = clothesItems[0][productName][0].sizes;
console.log(productName);
console.log(productSizes);
}
}
In our project we are getting below data from DB in following format.
[
[
"ClearDB",
"test1#test.com",
"com.test.cleardb"
],
[
"Cricbuzz",
"test2#test.com",
"com.test.cricbuzz"
],
[
"Hangout",
"test3#test.com",
"com.test.hangout"
]
]
I want this in key value format as mentioned below
[
{
"projname": "ClearDB",
"projmanager": "test1#test.com",
"package": "com.test.cleardb"
},
{
"projname": "Cricbuzz",
"projmanager": "test2#test.com",
"package": "com.test.cricbuzz"
},
{
"projname": "Hangout",
"projmanager": "test3#test.com",
"package": "com.test.hangout"
}
]
Please provide me a proper way to implement this.
You can simply create a new object for each of the arrays, and create an array of objects with map function, like this
var keys = ["projname", "projmanager", "package"];
console.log(data.map(function (arr) {
var obj = {};
keys.forEach(function (key, idx) { obj[key] = arr[idx]; });
return obj;
}));
Output
[ { projname: 'ClearDB',
projmanager: 'test1#test.com',
package: 'com.test.cleardb' },
{ projname: 'Cricbuzz',
projmanager: 'test2#test.com',
package: 'com.test.cricbuzz' },
{ projname: 'Hangout',
projmanager: 'test3#test.com',
package: 'com.test.hangout' } ]
with Array.prototype.map:
var results = db.map(function (v) {
return {
projname: v[0],
projmanager: v[1],
package: v[2]
};
});
Suppose the data you are getting from database is stored in variable 'abc'
var abc = [];
var output = [];
for(var i = 0; i< abc.length; i++){
output[i] = {};
output[i].projname = abc[i][0];
output[i].projmanager = abc[i][1];
output[i].package = abc[i][2];
}
Note: 'abc' is the variable where you are storing data from DB.
In ES6:
input . map(([projname, projmanager, package]) => ({projname, projmanager, package}));
The part in [] deconstructs the parameter to map, which is one of the subarrays, assigning the first element to projname, and so on. The part in {} creates and returns an object with a key of 'projname' whose value is projname, etc.
If you want to generalize this to use any array of field names (['projname', 'projmanager', 'package']):
input . map(
values =>
values . reduce(
(result, value, i) => {
result[fieldnames[i]] = value;
return result;
},
{}
)
);
if
var array =[
[
"ClearDB",
"test1#test.com",
"com.test.cleardb"
],
[
"Cricbuzz",
"test2#test.com",
"com.test.cricbuzz"
],
[
"Hangout",
"test3#test.com",
"com.test.hangout"
]
];
then
var obj = [];
array.each(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});
Edit:
Using Jquery
var obj = [];
$.each(array,function(key,value){ obj.push({"projname": value[0],
"projmanager":value[1],
"package": value[2]})
});
Using javascript
var obj = [];
array.forEach(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});
I am getting JSON data like below example. Now I want get each value in separate variables like
var reviewDate ='2015-06-01T05:00:00Z'
var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie
var reviewers = 'mike,john'
var title='Test project'
var call =$.ajax({
url:url,
type:"GET",
dataType:"json",
headers:{
Accept:"application/json;odata=verbose"
}
});
call.done(function(data,textStatus,jqXHR){
alert("Success!! "+ jqXHR.responseText);
});
call.fail(function(jqXHR,textStatus,errorThrown){
alert("Error retriving Tasks!! "+ jqXHR.responseText);
});
I am getting results in call.done in . How to set those values?
You could do something along these lines:
http://jsfiddle.net/e0mfc1rd/2/
Javascript:
var data = {
results: {
Date_x0020_of_x0020_Review: '2015-06-01T05:00:00Z',
Name_x0020_of_x0020_Developers: {
results: [
{
__metadata: {},
Title: 'Ankur Shah'
},
{
__metadata: {},
Title: 'Tony Liu'
},
{
__metadata: {},
Title: 'Qiuming Jie'
}
]
},
Name_x0020_of_x0020_Reviewers: {
results: [
{
__metadata: {},
Title: 'Mike'
},
{
__metadata: {},
Title: 'John'
}
]
}
}
}
// map the key names.
// you could do something more clever here, like just extracting
// the segment after the last underscore using substring or a regex,
// but for this example we'll do a simple map.
var names = {
'Name_x0020_of_x0020_Reviewers': 'reviewers',
'Name_x0020_of_x0020_Developers': 'developers'
}
// a variable to hold the result.
var processed = {};
// iterate over each key in data.results
// (e.g. 'Name_x0020_of_x0020_Developers', 'Name_x0020_of_x0020_Reviewers', etc.)
Object.keys(data.results).forEach(function(k) {
// if the object indexed at that key has a 'results' property that is an array...
if (Array.isArray((data.results[k] || {}).results)) {
// pluck the Title attribute from each of those entries into a new array.
var values = data.results[k].results;
var titles = values.map(function(v) {
return v.Title;
});
// translate keys like 'Name_x0020_of_x0020_Reviewers'
// into something more palatable
var key = names[k] || k;
// join the titles into a string, separated by a comma
processed[key] = titles.join(',');
}
else if (k.indexOf('Date') === 0) { // key starts with 'Date'
processed[k] = new Date(data.results[k]);
}
});
After which the variable 'processed' would contain:
{
"Date_x0020_of_x0020_Review": "2015-06-01T05:00:00.000Z",
"developers": "Ankur Shah,Tony Liu,Qiuming Jie",
"reviewers": "Mike,John"
}
You could also use UnderscoreJS to get your data from your JSON.
You need to chain some pluck calls and you should get to your data.
Please find the demo below and here at jsFiddle.
To get the parsed object into your comma separated format just use for example: var developers = parsed.developers.join(',');
var resultJSON = {
d: {
__metadata: {},
"Name_x0020_of_x0020_Developers": {
"results": [{
"Title": "Ankur Shah"
}, {
"Title": "Srikanth"
}, {
"Title": "Tony Liu"
}]
},
"Name_x0020_of_x0020_Reviewers": {
"results": [{
"Title": "Name1"
}, {
"Title": "Name2"
}, {
"Title": "Name3"
}]
}
}
};
//console.log(resultJSON);
var names = {
developers: 'Name_x0020_of_x0020_Developers',
reviewers: 'Name_x0020_of_x0020_Reviewers'
};
var parsed = {};
_.each(names, function (name, key) {
parsed[key] = _.chain(resultJSON) // key is developers, reviewers
.pluck(name) // is the name in the JSON e.g. Name_..._Developers
.pluck('results')
.tap(function (data) { // tap is optional and can be removed
console.log('before flatten', data); // it shows the nesting [[]]
})
.flatten(true) // used to remove outer array
.tap(function (data) {
// we now have the result. Next, get the title
console.log('before getting the Title', data);
})
.pluck('Title')
.value();
});
console.log(parsed);
document.getElementById('output').innerHTML = JSON.stringify(parsed, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<pre id="output"></pre>
Below is the JSON data.
JSON :
[{
"Code":"US-AL",
"Name":"Alabama",
"Population":4833722
},
{
"Code":"US-AK",
"Name":"Alaska",
"Population":735132
},
{
"Code":"US-AZ",
"Name":"Arizona",
"Population":6626624
},
{
"Code":"US-AR",
"Name":"Arkansas",
"Population":2959373
},
{
"Code":"US-CA",
"Name":"California",
"Population":38332521
},
{
"Code":"US-CO",
"Name":"Colorado",
"Population":5268367
},
{
"Code":"US-CT",
"Name":"Connecticut",
"Population":3596080
}]
I wanted to convert that data to this format.
[{
"US-AL": {
"name" : "Alabama",
"population" : 4833772
},
"US-AK": {
"name" : "Alaska",
"population" : 735132
}
}]
I tried with this function and separated the name and population from it.
var ParentData = [];
var ChildData = {"name": [], "population": []};
data.forEach(function(val, i) {
ParentData.push(val.Code);
ChildData.name.push(val.Name);
ChildData.population.push(val.Population);
})
But I'm not that expert in this. Just a learner and I don't know how to push to the parent data which gets aligned to it respectively.
Any help will be very much helpful for me to achieve this.
Thanks in advance.
Try this:
var newData = {};
data.forEach(function(val) {
newData[val.Code] = {name: val.Name, population: val.Population};
});
Keep in mind that forEach isn't natively supported by IE8-, although it can be polyfilled. This works in every browser:
for (var i = 0; i < data.length; i++)
newData[data[i].Code] = {name: data[i].Name, population: data[i].Population};
Or, since you added the "jquery" tag, you can also use:
$.each(data, function() {
newData[this.Code] = {name: this.Name, population: this.Population};
});
Try with native map of javascript
var newData = data.map(function (obj) {
var newObj = {};
newObj[obj.Code] = {};
newObj[obj.Code].name = obj.Name;
newObj[obj.Code].population = obj.Population;
return newObj;
});
console.log(newData)
[{
"US-AL":{
"name":"Alabama",
"population":4833722
}
},
{
"US-AK":{
"name":"Alaska",
"population":735132
}
},
{
"US-AZ":{
"name":"Arizona",
"population":6626624
}
},
{
"US-AR":{
"name":"Arkansas",
"population":2959373
}
},
{
"US-CA":{
"name":"California",
"population":38332521
}
},
{
"US-CO":{
"name":"Colorado",
"population":5268367
}
},
{
"US-CT":{
"name":"Connecticut",
"population":3596080
}
}
]
And the code:
var newDatas = datas.map(function(item) {
var obj = {};
obj[item.Code] = { name: item.Name, population: item.Population };
return obj;
});
datas is the array containing your original source.
I am trying to convert a JSON string in a Javascript object literal. I think it is possible with some loops, but i couldn't get it done. The target structure is shown below, "chartData".
Fiddle can be found here: http://jsbin.com/ajemih/13/edit
Here's the JSON data:
{
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
}
This should it look like after the conversion:
chartData = [[['loadMovement', 111],
['allMovement', 120],
['allLoad', 130]],
[['Load+Move', 671],
['allMovement', 280],
['allLoad', 910]]];
I think this would work:
Working demo: http://jsfiddle.net/jfriend00/YmjDR/
var data = {
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
};
var chartData = [];
for (var i in data) {
var item = data[i];
var outer = [];
// skip over items in the outer object that aren't nested objects themselves
if (typeof item === "object") {
for (var j in item) {
var temp = [];
temp.push(j);
temp.push(item[j]);
outer.push(temp);
}
}
if (outer.length) {
chartData.push(outer);
}
}
You could do something like this:
var chartData = []
for(var key in data) {
var properties = data[key];
if(typeof properties === "object") {
var array = [];
for(var propKey in properties) {
array.push([propKey, properties[propKey]])
}
chartData.push(array);
}
}
Check out the fiddle.
You need to map the data manually. Thats actually more a diligent but routine piece of work.
var jsonData = 'your json string';
Object.keys( jsonData ).map(function( key ) {
if( typeof jsonData[ key ] === 'object' ) {
return Object.keys( jsonData[ key ] ).sort(function( a, b ) {
return +jsonData[ key ][ a ] - +jsonData[ key ][ b ];
}).map(function( name ) {
return [ name, jsonData[ key ][ name ] ];
});
}
}).filter( Boolean );
The above code will sort each group by its numeric value and then map a new array in the required style. Since .map() possibly returns undefined values on non-object elements, we need to filter those out before or afterwards.
See http://jsfiddle.net/WjZB2/2/
I had similar problem.
My goal was to convert a list of strings into a valid format for http://ivantage.github.io/angular-ivh-treeview/
This was my starting point:
[
"A\\A1\\Test1",
"A\\A1\\Test2",
"A\\A2\\Test3",
"B\\Test4",
"B\\Test5",
"B\\B1\\Test6",
"B\\B1\\Test7",
"B\\B1\\Test8",
"C\\C1\\C1a\\Test9",
"C\\C1\\C1b\\Test10",
"C\\C2\\C2a\\Test11",
"C\\C2\\C2a\\Test12",
"C\\C2\\C2a\\Test13",
"C\\C3\\Test14",
"C\\Test15",
"C\\Test16"
]
And I needed following format:
[
{
"label": "Selected Tests",
"children": [
{
"label": "A",
"children": [
{
"label": "A1",
"children": [
{
"label": "Test1",
"value": true
},
{
"label": "Test2",
"value": true
}
]
},
{
"label": "A2",
"children": [
{
"label": "Test3",
"value": true
}
]
}
]
}
]
}
]
See my solution https://jsfiddle.net/ydt3gewn/