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);
}
}
Related
I'm trying to collate some data. I would like to populate an array containing sub arrays, for example, I have some json data that I am iterating over:
{
"name": "name1",
"prices": "209.67"
},
{
"name": "name1",
"prices": "350"
},
{
"name": "name2",
"price": "195.97"
},
I would like to create an array that ends up looking something like the following:
myArray['name1']prices[0] = 209.67,
prices[1] = 350,
['name2']prices[0] = 195.97
I thought that the code below would achieve what I wanted but it doesn't work. It throws an exception. It doesn't seem to recognise the fact that the prices are an array for a given index into the main array. Instead the prices appear at the same level as the names. I want the main array for a given name to contain an inner array of prices.. Does anybody have any idea how I could modify to make this work?
function doStuff() {
var cryptoData = getData();
var datasetValues = {};
datasetValues.names = [];
datasetValues.names.prices = [];
for (var result = 0; result < cryptoData.length; result++) {
var data = cryptoData[result];
if (datasetValues.names.indexOf(data.cryptoname) === -1)
{
datasetValues.names.push(data.cryptoname);
}
// This works
//datasetValues.names.prices.push(data.prices);
// This doesn't!
datasetValues.cryptoNames[data.cryptoname].prices.push(data.prices);
}
}
You could reduce the array by using an object and take a default object if the property is not set. Then push the price.
var data = [{ name: "name1", price: "209.67" }, { name: "name1", price: "350" }, { name: "name2", price: "195.97" }],
result = data.reduce((r, { name, price }) => {
r[name] = r[name] || { name, prices: [] };
r[name].prices.push(+price);
return r;
}, Object.create(null));
console.log(result);
Try this
function parseData(input){
return input.reduce(function(o,i){
o[i.name] = {};
if(!o[i.name]['prices']){
o[i.name]['prices'] = [];
}
o[i.name]['prices'].push(i.prices);
return o;
},{});
}
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
var basicS = {
"question":[]
}
data.forEach(function(val,i){
x1[val.name]=basicS;
});
console.log(x1);
data.forEach(function(val,i){
x1[val.name].question.push('insert');
});
console.log(x1);
Output:
{
123123123123:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123124:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123125:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123126:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
}
}
Expected Output should be:
{
123123123123:{
question:[
0:"insert"
]
},
123123123124:{
question:[
0:"insert"
]
},
123123123125:{
question:[
0:"insert"
]
},
123123123126:{
question:[
0:"insert"
]
}
}
Not able to understand from where four values are inserted inside the each question array while i am inserting only one in each question
array object.
Is there any alternative to solve this type of prblem.
Please help me out. I am totally confused. Thanks in advance.
You may want to create multiple objects:
data.forEach(function(val,i){
x1[val.name]={
"question":[]
};
});
Or both loops in one O(n) instead of O(2n):
data.forEach(function(val,i){
(x1[val.name]=x1[val.name] || {question:[]}).question.push(val);
});
This is happening because every value in x1 is referencing the same basicS array. So you are pushing insert into that array four times.
To avoid this, give each item in x1 a new array:
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
data.forEach(function(val,i){
x1[val.name]= { "question": [] };
});
data.forEach(function(val,i){
x1[val.name].question.push('insert');
});
console.log(x1);
Or, depending on what you're ultimately trying to do, you could just populate the arrays with their initial value instead of looping twice:
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
data.forEach(function(val,i){
x1[val.name] = { "question": ["insert"] };
});
console.log(x1);
Keep it simple.
Use a new object as your container to populate.
Switch from "forEach" to "for" loop to avoid confusion.
Create a new instance of the array on every iteration for reference.
Assign index at 0 to insert.Take object at iteration and set it the name property value.
Then assign to an Object with the question property set to your array at key '0'
var data = [{
"name": "123123123123"
},
{
"name": "123123123124"
},
{
"name": "123123123125"
},
{
"name": "123123123126"
}
];
var obj = {};
for (var i = 0; i < data.length; i++) {
var insert = [];
insert['0'] = 'insert';
obj[data[i].name] = {
question: insert
}
};
console.log(obj);
I have an array of objects, say the object looks like following:
var row = {
data: 'test',
text: 'test'
};
I want to loop through the array and just get the object with text property.
What is the best way to do it?
So, I want to loop and the object should look like: row = {text: 'test'}
I tried something like below without luck:
arr.forEach(function (item){ //arr is the array of object
return {text: item.text};
});
Use Array.prototype.map for that:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
return {text: item.data};
});
The result will look like:
[{ text: 'testData' }]
If you want it to be [ {testText: 'testData' }] then:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
var obj = {};
obj[item.text] = item.data;
return obj;
});
As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.
var array = [
{
text : "text",
data : "data"
},
{
text : "text1",
data : "data1"
}
]
var newArray = array.map(function(item){
return item.data;
});
your output will look like
['text','text1']
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);
I have a function (that I can't change) that queries data from a database and returns it in a variable that shows as the following format if I display it as text:
var outputdata=
[
{ itemA: 'M0929', itemDate: new Date(1950,03-1,25,0,0,0,0), itemID: 'JDR12' },
{ itemA: 'X0121', itemDate: new Date(1983,07-1,07,8,0,0,0), itemID: 'RPN50' },
{ itemA: 'U0229', itemDate: new Date(1942,09-1,07,8,0,0,0), itemID: 'CRG98' },
];
I need it to be converted into the following format (specific date formatting doesn't matter) for use by another function (that I also can't change).
var inputdata=[
[
"M0929",
"1950-03-25",
"JDR12"
],
[
"X0121",
"1983-07-07",
"RPN50"
],
[
"U0229",
"1942-09-07",
"CRG98"
]
];
Could someone offer some assistance... I don't really understand javascript arrays and I'm really after a function to do the conversion.
You're probably going to have to write it yourself, for example:
function pad (what)
{
return what < 10 ? '0'+what : String(what);
}
function transformData (data)
{
var result = [];
for (var i=0;i<data.length;++i)
{
var date = data[i]['itemDate'];
result.push([
data[i]['itemA'],
date.getFullYear()+'-'+pad(date.getMonth())+'-'+pad(date.getDate()),
data[i]['itemID']
]);
}
return result;
}
var outputdata=
[
{ itemA: 'M0929', itemDate: new Date(1950,03-1,25,0,0,0,0), itemID: 'JDR12' },
{ itemA: 'X0121', itemDate: new Date(1983,07-1,07,8,0,0,0), itemID: 'RPN50' },
{ itemA: 'U0229', itemDate: new Date(1942,09-1,07,8,0,0,0), itemID: 'CRG98' },
];
var result = transformData(outputdata);
alert(result.join("\n"));
Now, the things to be aware of are the nature of UTC dates. More details can be found here http://www.w3schools.com/jsref/jsref_obj_date.asp. Also, I highly recommend reading more about Javascript in general.
function convert(outputdata){
var arr = [];
for(var i = 0; i<outputdata.length; i++){
var output = outputdata[i];
var temp = [output.itemA, output.itemDate, output.itemID];
arr[i] = temp;
}
return arr;
}
Edited: initialized arr.
Not a full response, because this smells like homework (and if it is, you should tag it as such). So hints first:
You can make an array by writing something like `[ 7, 9*7, "ho" ]
You can get at properties with dot notation like obj.itemA