How to insert same item into nested array. Here is my input element.
var myData1 = [{data1: 1},{data2:2}];
var myData2 = [{data1: 1},{data2:2}];
var myData3 = [{data1: 1},{data2:2}];
var key = [myData1, myData2, myData3];
var myVale = {
someValue :"SomeValue",
myData: [],
myVal: []
}
ANd this is my expected o/p
var myVale = {
someValue :"SomeValue",
myData: myData1,
myVal:[{someValue :"SomeValue",
myData: myData2,
myVal : [{
someValue :"SomeValue",
myData: myData3,
}]
}]
}
What I am trying here is
for(var i=0; i<key.length;i++){
myVale.myVal.push(myVale);
myVale.myData.push(key[i])
}
But here I am not getting an expected result. The output is going into loop. Any suggestion how I can get that?
I changed the input to ensure it is working as expected
var myData1 = [{data11: 1},{data12:2}];
var myData2 = [{data21: 1},{data22:2}];
var myData3 = [{data31: 1},{data32:2}];
var key = [myData1,myData2,myData3];
var myVale = {};
var index = 0;
function formatJSON(key, index) {
var tempVale = {};
tempVale.someValue = "SomeValue"+index;
tempVale.myData = key[index];
if(++index >= key.length)
return tempVale;
tempVale.myVal = formatJSON(key, index);
return tempVale;
}
myVale = formatJSON(key, index);
console.log(myVale);
console.log(JSON.stringify(myVale));
Related
So I have three nested associative objects/arrays in total. Employee1 and employee2 were first made, and then employees was created in order to nest the two associative objects. Next, I created a third associative object, employee3, to nest into the employees object. What I am trying to do now is filter through the 2D array using the .filter() method to only bring up the employees that are currently working there, which is indicated in the arrays by ["isCurrent"] = true; but all I'm getting in the console window is undefined. Why is this happening and how do I fix this?
var employee1 = [];
employee1["id"] = 33;
employee1["name"] = "Carey Shanks";
employee1["title"] = "Knife Maker";
employee1["department"] = "fabrication";
employee1["isCurrent"] = true;
var employee2 = [];
employee2["id"] = 34;
employee2["name"] = "Giles Newman";
employee2["title"] = "Lead Sales";
employee2["department"] = "Customer Service";
employee2["isCurrent"] = true;
var employees = [];
employees[0] = [];
employees[0]["id"] = 33;
employees[0]["name"] = "Carey Shanks";
employees[0]["title"] = "Knife Maker";
employees[0]["department"] = "fabrication";
employees[0]["isCurrent"] = true;
var employee3 = [];
employee3["id"] = 35;
employee3["name"] = "Tori G.";
employee3["title"] = "Product Demonstrator";
employee3["department"] = "Marketing";
employee3["isCurrent"] = false;
//MERING THE ARRAYS
employees.push(employee2);
employees.push(employee3);
//TESTING TO SEE IF IT POPULATED
//window.console.log(employees);
var i;
var currentEmployee = function (isCurrent) {
var isCurrentEmployee = true;
for (i in employees) {
if (isCurrent !== true) {
isCurrentEmployee = false;
break;
}
}
return isCurrentEmployee;
};
var isCompanyEmployee = employees.filter(currentEmployee);
window.console.log(isCompanyEmployee[i]);
Some issues:
Arrays should only be used with numeric indicies. If you want to use arbitrary string keys, use an object instead.
The first argument to the filter callback is the current item being iterated over; your
var currentEmployee = function (isCurrent) {
defines isCurrent as the first argument, but that's not the isCurrent property. If you wanted to immediately extract the isCurrent property from the object, destructure the parameter instead, and then you can just return it:
var currentEmployee = function ({ isCurrent }) {
return isCurrent;
}
Or, if you're not comfortable with destructuring, this is equivalent to
var currentEmployee = function (employee) {
return employee.isCurrent;
}
i has no meaning outside the currentEmployee function - log the filtered array instead:
console.log(isCompanyEmployee);
You never push employee1 to the array.
var employee1 = {};
employee1["id"] = 33;
employee1["name"] = "Carey Shanks";
employee1["title"] = "Knife Maker";
employee1["department"] = "fabrication";
employee1["isCurrent"] = true;
var employee2 = {};
employee2["id"] = 34;
employee2["name"] = "Giles Newman";
employee2["title"] = "Lead Sales";
employee2["department"] = "Customer Service";
employee2["isCurrent"] = true;
var employees = [];
employees[0] = {};
employees[0]["id"] = 33;
employees[0]["name"] = "Carey Shanks";
employees[0]["title"] = "Knife Maker";
employees[0]["department"] = "fabrication";
employees[0]["isCurrent"] = true;
var employee3 = {};
employee3["id"] = 35;
employee3["name"] = "Tori G.";
employee3["title"] = "Product Demonstrator";
employee3["department"] = "Marketing";
employee3["isCurrent"] = false;
//MERING THE ARRAYS
employees.push(employee1);
employees.push(employee2);
employees.push(employee3);
//TESTING TO SEE IF IT POPULATED
//window.console.log(employees);
var i;
var currentEmployee = function ({ isCurrent }) {
return isCurrent;
};
var currentEmployees = employees.filter(currentEmployee);
window.console.log(currentEmployees);
From my data source I am getting values like;
USA |Arizona
USA |Florida
UK |England |Northamptonshire
UK |England |Derbyshire
UK |Wales |Powys
Switzerland|Lucern
These are flat text values that repeat in a column.
I need to build them dynamically into nested array
source: [
{title: "USA", children: [
{title: "Arizona"},
{title: "Florida"}
]}
],
As per https://github.com/mar10/fancytree/wiki/TutorialLoadData
Unfortunately my brain has stopped working today I am can't see a elegant way.
Any pointers would be most gratefully appreciated.
So I solved this eventually using a post from Oskar
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
http://oskarhane.com/create-a-nested-array-recursively-in-javascript/
This builds the nested array.
To ensure inferred values were present (e.g. USA which is in the hierarchy but is not a unique value).
var CountryArray = CountryText.split("|");
// Variables to hold details of each section of the Country path being iterated
var CountryId = '';
var CountryParentPrefix = '';
var CountryParent = '';
// Iterate each section of the delimeted Country path and ensure that it is in the array
for(var i in CountryArray)
{
var CountryId = CountryParentPrefix+CountryArray[i];
// Find the Country id in the array / add if necessary
var result = FlatSource.filter(function (Country) { return Country.id == CountryId });
if (result.length == 0) {
// If the Country is not there then we should add it
var arrCountry = {title:CountryArray[i], parent:CountryParent, id:CountryId};
FlatSource.push(arrCountry);
}
// For the next path of the heirarchy
CountryParent = CountryId;
CountryParentPrefix = CountryId+'|';
}
I did not use Sven's suggestion but I suspect that it is equally valid.
Turn it to JSON:
var str = '"USA|Arizona","USA|Florida","UK|LonelyIsland","UK|England|Northamptonshire","UK|England|Derbyshire","UK|Wales|Powys","UK|England|London|Soho","Switzerland|Lucern';
var jsonStr = "[[" + str.replace(/,/g,'],[') + "\"]]";
jsonStr = jsonStr.replace(/\|/g,'","');
var nested = JSON.parse(jsonStr);
Then play with parents and children.
function findObject(array, key, value) {
for (var i=0; i<array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
function obj(arr){
this.title = arr.shift();
}
obj.prototype.addChild = function(arr){
var tmp = new obj(arr);
if(typeof this.children === 'undefined'){
this.children = new Array();
result = this.children[this.children.push(tmp)-1];
}else{
result = findObject(this.children, 'title', tmp.title);
if(!result)
result = this.children[this.children.push(tmp)-1];
}
return result;
}
obj.prototype.addChildren = function(arr){
var obje = this;
while(arr.length>0)
obje = obje.addChild(arr);
}
var finArr = [];
for(i=0; i<nested.length; i++){
var recc = new obj(nested[i]);
if(oldObj = findObject(finArr, 'title', recc.title)){
oldObj.addChildren(nested[i]);
}else{
if(nested[i].length>0)
recc.addChildren(nested[i]);
finArr.push(recc);
}
}
console.log('------------------------------------------')
console.log(JSON.stringify(finArr));
console.log('--------------------The End---------------')
I have this code, but for some reason I keep getting colours.undefined
var varray = new Array("WH", "BL");
var fname = "colours",
lname = "size_code_id";
var arr = new Array();
var mquery = {
"$or": []
};
for (var i = 0; i < varray.length; i++); {
var query = {
"$and": []
};
var s1 = fname.concat(".").concat(varray[i]);
var s2 = fname.concat(".").concat(varray[i]).concat(".").concat(lname);
var sub1 = {}, sub2 = {};
sub1[s1] = {
$exists: 1
};
sub2[s2] = "S";
query["$and"].push(sub1);
query["$and"].push(sub2);
arr.push(query);
};
I want to get colours.WH.size_code_id but keep getting colours.undefined.size_code_id
What am i missing, any advice much appreciated
Remove ; after
for (var i = 0; i < varray.length; i++) ; {
Example
var varray = new Array("WH", "BL");
var fname = "colours",
lname = "size_code_id";
var arr = new Array();
var mquery = {
"$or": []
};
for (var i = 0; i < varray.length; i++) {
var query = {
"$and": []
};
var s1 = fname.concat(".").concat(varray[i]);
var s2 = fname.concat(".").concat(varray[i]).concat(".").concat(lname);
var sub1 = {}, sub2 = {};
sub1[s1] = {
$exists: 1
};
sub2[s2] = "S";
query["$and"].push(sub1);
query["$and"].push(sub2);
arr.push(query);
};
console.log(arr)
I want to transform this object so that I can call it that way
cars.ox, bikes.ox
var baseValue = [
{
'2014-12-01': {
'cars;ox;2014-12-01':100,
'cars;ot;2014-12-01':150,
'bikes;ox;2014-12-01':50,
'bikes;ot;2014-12-01':80
},
'2014-12-02': {
'cars;ox;2014-12-02':100,
'cars;ot;2014-12-02':150,
'bikes;ox;2014-12-02':50,
'bikes;ot;2014-12-02':80
}
}
]
I try do this in many ways, but at the end i completely lost all hope.
var category = []
var obj = baseValue[0]
Object.keys(obj).forEach(function(key) {
var dane = obj[key]
Object.keys(dane).forEach(function(key) {
splitted = key.split(';')
var category = splitted[0]
var serviceName = splitted[1];
})
})
I would be grateful if anyone help me with this
I think you were close, you just need to create objects if they do not exist for the keys you want. Perhaps something like this.
var obj = baseValue[0]
var result = {};
Object.keys(obj).forEach(function(key) {
var dane = obj[key]
Object.keys(dane).forEach(function(key) {
splitted = key.split(';')
var category = splitted[0]
var serviceName = splitted[1];
if(!result[category]) {
result[category] = {};
}
if(!result[category][serviceName]) {
result[category][serviceName] = [];
}
result[category][serviceName].push(dane[key]);
})
});
http://jsfiddle.net/6c5c3qwy/1/
(The result is logged to the console.)
I'm really new to JS, and I'm now stuck on a task, hope someone can guide me through it.
I have an Array of Objects, like this one:
var labels = [
// labels for pag 1
{pageID:1, labels: [
{labelID:0, content:[{lang:'eng', text:'Txt1 Eng'}, {lang:'de', text:'Txt1 De:'}]},
{labelID:1, content:[{lang:'eng', text:'Txt 2 Eng:'}, {lang:'de', text:'Txt2 De:'}]},
{labelID:2, content:[{lang:'eng', text:'Txt 3 Eng:'},{lang:'de', text:'Txt 3 De:'}]}
]},
// labels for pag 2
{pageID:2, labels: [
{labelID:0, content:[{lang:'eng', text:'Txt1 Eng'}, {lang:'de', text:'Txt1 De:'}]},
{labelID:1, content:[{lang:'eng', text:'Txt 2 Eng:'}, {lang:'de', text:'Txt2 De:'}]},
{labelID:2, content:[{lang:'eng', text:'Txt 3 Eng:'},{lang:'de', text:'Txt 3 De:'}]}
]}
]
What I am trying to do is write a function to return me an array of labels (Objects) for a specific page and a specific lang. By calling this function specifying pageID 1 and lang eng, I'm basically trying to build an array like this one:
var desideredArray = [
{labelID:0, text:'Txt1 Eng'},
{labelID:1, text:'Txt1 Eng'},
{labelID:2, text:'Txt2 Eng'}
]
Now, I'm trying to write the function to retrieve/build the new array:
this.getLabelsForPageAndLang = function (numPage, lang) {
// this part filters the main object and selects the object with pageID == numPage
var result = labels.filter(function( obj ) {
return obj.pageID == numPage;
});
var tempResult = result[0].labels;
var desiredResults = []; // here I want to store the new objects
for (var i=0; i<tempResult.length; i++) {
var simpleLabelObject = {};
simpleLabelObject.labelID = tempResult[i].labelID;
// simpleLabelObject.text = ?????
results[i] = simpleLabelObject;
}
console.log (results);
};
...but how can I access the right value (the one corresponding the lang selected) in the content property?
You can use the same technique as the one used to keep the matching page: the filter method.
this.getLabelsForPageAndLang = function (numPage, lang) {
// this part filters the main object and selects the object with pageID == numPage
var result = labels.filter(function( obj ) {
return obj.pageID == numPage;
});
var contentFilter = function(obj){ return obj.lang === lang};
var tempResult = result[0].labels;
var desiredResults = []; // here I want to store the new objects
for (var i=0; i<tempResult.length; i++) {
var simpleLabelObject = {};
simpleLabelObject.labelID = tempResult[i].labelID;
var matching = tempResult[i].content.filter(contentFilter);
simpleLabelObject.text = matching[0].text;
desiredResults[i] = simpleLabelObject;
}
console.log (desiredResults);
};
I didn't do bound checks because in your code you assumed there is always a matching element, but it would probably be wise to do it.
And if you want to avoid creating two closures each time the function is called, you can prototype an object for that:
var Filter = function(numPage, lang) {
this.numPage = numPage;
this.lang = lang;
};
Filter.prototype.filterPage = function(obj) {
return obj.pageID === this.numPage;
}
Filter.prototype.filterLang = function(obj) {
return obj.lang === this.lang;
}
Filter.prototype.filterLabels = function(labels) {
var result = labels.filter(this.filterPage, this);
var tempResult = result[0].labels;
var desiredResults = []; // here I want to store the new objects
for (var i=0; i<tempResult.length; i++) {
var simpleLabelObject = {};
simpleLabelObject.labelID = tempResult[i].labelID;
var matching = tempResult[i].content.filter(this.filterLang, this);
simpleLabelObject.text = matching[0].text;
desiredResults[i] = simpleLabelObject;
}
return desiredResults;
}
console.log(new Filter(1, "eng").filterLabels(labels));
Just filter again:
var getLabelsForPageAndLang = function (numPage, lang) {
// this part filters the main object and selects the object with pageID == numPage
var result = labels.filter(function (obj) {
return obj.pageID == numPage;
});
var tempResult = result[0].labels;
var desiredResults = []; // here I want to store the new objects
for (var i = 0; i < tempResult.length; i++) {
var simpleLabelObject = {};
simpleLabelObject.labelID = tempResult[i].labelID;
var lg = tempResult[i].content.filter(function (lg) {
return lg.lang == lang;
});
simpleLabelObject.text = lg[0].text;
desiredResults.push(simpleLabelObject);
}
console.log(desiredResults);
};
http://jsfiddle.net/9q5zF/
A rather 'safe' implementation for cases when pages have the same pageID and multiple contents with the same lang:
this.getLabelsForPageAndLang = function(numPage, lang) {
var result = [];
var pages = labels.filter(function( obj ) {
return obj.pageID === numPage;
});
for (var p = pages.length - 1; p >= 0; p--) {
var page = pages[p];
for(var i = page.labels.length - 1; i >= 0; i--) {
var labelId = page.labels[i].labelID;
for (var j = page.labels[i].content.length - 1; j >= 0; j--){
if (page.labels[i].content[j].lang === lang) {
result.push({labelID: labelId, test: page.labels[i].content[j].text});
}
}
}
}
console.log(result);
}
Fiddle: http://jsfiddle.net/6VQUm/