javascript array in array - javascript

I am building a file management system for the web right now.
But I have some problems with javascript array's.
In the system there is an opportunity to add labels to file's.
In javascript I want to have the ID and the value's of the labels with the fileId in 1 array.(as below).
I also want the FileId and the LabelId not as the index of the array's. Because the FileId and labelId can be a realy high number. And then I have an array full of undefined items.
Here an example of how I would like to have it:
array[FileId][labelId,labelValue]
If you have an solution please help me.
Thanks.

You can form structure like this:
arr = [{FieldId:fid_value, Labels:[{labelId:lid_value, labelValue:label_text}]}]
Basically, an array with objects. Each object contains two fields: field id and labels.
Labels is an array with objects also. Each object has label id and label value property.
Code to create new items might be like this:
arr = array();
fieldObj = {FieldId:fid_value, Labels:[]};
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
...
arr.push(fieldObj);

I'm not entirely sure what you're asking but array within array is possible...
a = []
a.push('a')
Result:
["a"]
a.push(['hello','world'])
Result:
["a",
Array[2]
0: "hello"
1: "world"
]

It sounds like you want objects instead of arrays:
var obj = {};
obj["fieldName"] = {label: "labelname", labelId: 1234};
Then you can access this data as:
obj["fieldName"].label

You could also use an object
var data = {};
data["item1"] = { "labelId" : "foo1", "labelValue" : "bar1" };
data["item2"] = { "labelId" : "foo2", "labelValue" : "bar2" };
console.log(data.item1.labelId);
There are plenty of ways you can strcture the object, it is normally better to use an object than to remember that index 0 is the id and that index 1 is a value.

Use should use objects as well as arrays:
var root = [{
id: '12345',
metadata: {
label: 'foo',
},
type: 'folder',
name: 'Folder Name',
children: [...]
}
];
Now, you can iterate through the folders and files in your root:
for (var i = 0; i < root.length; i++) {
var item = root[i];
console.log(item.type, item.name, item.id);
}

Related

how to use lodashJs to group a result in angularjs

I'm trying to populate a tree component using angularjs via this JSON object:
var myData=[{"agence":"CTM","secteur":"Safi","serie":"CZC1448YZN"},{"agence":"CTM","secteur":"Safi","serie":"2UA13817KT"},{"agence":"CTM","secteur":"Rabat","serie":"CZC1349G1B"},{"agence":"CTM","secteur":"Rabat","serie":" 2UA0490SVR"},{"agence":"CTM","secteur":"Agdal","serie":" G3M4NOJ"},{"agence":"CTM","secteur":"Essaouira","serie":" CZC1221B85"},{"agence":"Gare Routiere Municipale","secteur":"Essaouira","serie":" CZC145YL3"}] ;
heres the javascript code :
var treedata_avm = [];
for(var i=0; i < myData.length; i++) {
// alert('roro '+myData[i].secteur);
treedata_avm.push({
label: myData[i].secteur,
children: [{
label: myData.agence,
children: [myData[i].serie]
}]
});
}
$scope.my_data = treedata_avm;
HTML:
<abn-tree tree-data="my_data " tree-control="my_tree" on-select="my_tree_handler(branch)" expand-level="2" initial-selection="Granny Smith" icon-leaf="ti-file" icon-expand="ti-plus" icon-collapse="ti-minus"></abn-tree>
it works fine but i didnt get the expected bevaviour which i want..what i want is to get the data group by secteur and agence like this:
-Safi
-CTM
CZC1448YZN
2UA13817KT
-Rabat
-CTM
CZC1349G1B
2UA0490SVR
-Agdal
G3M4NOJ
-Essaouira
-CTM
CZC1221B85
-Gare Routiere Municipale
CZC145YL3
You could use groupBy() to initialize the structure as you want:
myData = _.groupBy(this.myData, 'secteur');
But then you'd have to add in the appropriate extras (agence, serie etc) to each object.
Or you could use _.reduce() which would combine the two (which would probably be better for you). Remember that reduce() is also a method on arrays in Plain Ol' JavaScript so you're not forced to use lodash:
_.reduce(this.myData, function(acc, value, key) {
(result[key] || result[key] = value).push(acc);
return acc;
}, acc);

How to add value to javascript array two time or more?

This is my code, I have two array and want to put them in other array what named data:
data=[];
atIndex=0;
//userInfo is name and last name of user:
userInfo=['Mohammad','Kermani'];
//userKnow is stuff what a user know:
userKnow=['php','javascript'];
data[atIndex]=userInfo;
data[atIndex]=userInfo;
data[atIndex]=userKnow;
//I want to send data with json,and decode it with php:
console.log(data);
But now just the last data is in data
maybe it is nested array or two demential array
DEMO
You could make it an array of objects...
data[atIndex] = { userInfo: userInfo, userKnow, userKnow };
which would be accessible like so:
var userInfo = data[0].userInfo;
var userKnow = data[0].userKnow;
Your JSON would end up looking something like this (line breaks are for readability):
[
{ userInfo: ['Mohammad', 'Kermani'], userKnow: ['php', 'javascript'] }
]
Personally, if you are looking to send user information with an array of what they know then consider an object structure like this:
var userObject = {
name1: 'Mohammad',
name2: 'Kermani',
userKnow: ['php', 'javascript']
};
You can user this like so:
userObject.name1 = 'my name';// set name1
var name2 = userObject.name2;// get name2

How to define an empty javascript object with the following struture so that I can dynamically insert data into it?

I am using JIT Infovis stacked or mono-valued piechart to do some data visualization. The stacked pie chart takes an object "obj" specifically with the following structure:
This is the hard coded version of jsonObj:
var obj = {
// labelID is unique in each case and may be multiple or just one
'labelID': ['pVal'],
'values': [{ //labelName is unique in each case and will only be one
'labelName': 'name1',
//there may be multiple or just one "values"
//ex, 'values': [80, 40, 15, 10]
'values': 80
}, {
'labelName': 'name2',
'values': [20]
}, {
'labelName': 'name3',
'values': [38]
}, {
'labelName': 'name4',
'values': [58]
}]
};
I'm trying to dynamically populate "obj" with searched data returned to user. But I can not create an empty "obj" with the above specific structure to dynamically populate the data. I tried several times but don't think I'm creating them correctly.
I have three values that I'm trying to dynamically populate into this "obj" but can't get my arms around it. chartID[m], chartArrName[m], chartVal[m].
I need a correct empty "obj" that correspond to the structure defined above.
var "obj" = {
label: ['pVal'],
values: [{
label: [],
values: []
}]
};
for (m = 0; m <= chartArrID.length - 1; m++) {
obj.values[m].label += chartArrName[m];
obj.values[m].values += parseFloat(chartArrVal[m]);
//json.push({label: chartArrName[m], values: parseFloat(chartArrVal[m])});
}
This is not a JSON object. JSON is a lightweight data interchange format. You are just using a object initializer syntax to create an object. You can add what you want of the fly.
var myObj = {};
myObj.name = "foo";
myObj.books = [ "one", "two" ];
myObj.emptyField = null;
myObj.emptyArray = [];
myObj["anotherField"] = "bar"; // this works too
myObj.anotherArray = [];
myObj.anotherArray[0] = {}; // you need to insert something in the first position!
myObj.anotherArray[0].label = "aaa";
myObj.anotherArray[0].value = "bbb";
myObj.anotherArray[0].xyz = "ccc";
myObj.anotherArray[1] = {}; // in the second too, of course!
myObj.anotherArray[1].label = "ddd";
myObj.anotherArray[1].value = "eee";
myObj.anotherArray[1].xyz = "fff";

How to build a json object with a loop?

I'm trying to loop through a number of items, and create a json object. Each loop should be a new item on the object, but I'm having some issues doing it. It seems that only one set of items gets added, instead of multiple ones.
Here is my code:
jsonObj = {}
rows.each(function (index) {
jsonObj["id"] = $this.find('.elementOne').val();
jsonObj["name"] = $this.find('.elementTwo').text();
});
Here is what my json looks like:
{
id: "3"
name: "Stuff"
},
Here is what I am trying to do:
{
id: "1"
name: "Stuff"
},
{
id: "2"
name: "Stuff"
},
{
id: "3"
name: "Stuff"
}
There is no JSON here. Please don't confuse:
A JavaScript object (a data structure)
A JavaScript object literal (code to create such a data structure)
JSON (a data format based on a subset of object literal notation)
If you want an ordered list of objects (or any other kind of JavaScript data structure) then use an array. Arrays have a push method.
var myData = [];
rows.each(function (index) {
var obj = {
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
};
myData.push(obj);
});
You override the object instead of adding it a new value each iteration.
Fixed code using an array:
jsonObj = [];
rows.each(function(index) {
jsonObj.push({
'id': $this.find('.elementOne').val(),
'name': $this.find('.elementTwo').text()
});
});​
What you want is an array of objects. When you try to write the same property on the same object multiple times, it gets overwritten which is why you're seeing id and name contain values for the last iteration of the loop.
Although you haven't tagged the question with jQuery, it does look like jQuery, so here's a solution:
I've taken the liberty to change $this to this because $this seems to be referring to the same object in each iteration, which is now what you may want (methinks)
var myArray = rows.map(function() {
return {
id: $(this).find('.elementOne').val(),
name: $(this).find('.elementTwo').text()
};
});
You can do it like this with jquery. The function will expect form elements of type input. It will iterate over thr passed form and it will collect each input name and value and it will create a json object like
Exmple:
HTML
<form action="" method="post" id="myForm">
<input type="text" name="field1" value="I am value of field 1"/>
<input type="text" name="field2" value="I am value of field 2"/>
</form>
Javascript
function buildObject(form) {
var jsonObject = [],
tempObj = {};
$(form).find("input:not(input[type='submit'])").each(function() {
tempObj[$(this).attr("name")] = $(this).val();
});
jsonObject.push(tempObj);
return jsonObject[0];
}
buildObject($("#myForm"));
//Will produce
jsonObj = {
field1 : "I am value of field 1",
field2 : "I am value of field 2"
}
This is because you're merely overwriting the same properties of your object, id and name, each time. You need to be making a sub-object for each, then push it into the master object (which I've converted to array, since it's non-associative).
var jsonObj = []
rows.each(function (index) {
var temp_obj = {};
temp_obj["id"] = $this.find('.elementOne').val();
temp_obj["name"] = $this.find('.elementTwo').text();
jsonObj.push(temp_obj);
});
[EDIT] - as Mark Eirich's answer shows, the temp_obj is unnecessary - you could push an anonymous object instead, but I defined temp_obj just to make it crystal clear what's happening.
Also read Quentin's very good points re: common confusion between JavaScript objects and JSON.
var jsonObj = [];
rows.each(function(index) {
jsonObj.push({
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
});
});

Search a JavaScript object

I have a JavaScript object like this:
[{
name : "soccer",
elems : [
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
},
{
name : "basketball",
elems : [
{name : "Dallas Mavericks"}
]
}]
Now I want to search on this JavaScript object in the browser. The search for "FC" should give me something like this:
[
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
How to do this fast? Are there any JavaScript libs for this?
You might like using jLinq (personal project)
http://hugoware.net:4000/Projects/jLinq
Works like LINQ but for JSON and it allows you to extend it and modify it however you want to. There is already a bunch of prebuilt methods to check values and ranges.
Seeing as though the only helpful answers have been referencing third party libraries - here's your native javascript solution. For anyone that only wants a few lines of code rather than a stack:
The function:
Array.prototype.findValue = function(name, value){
var array = map(this, function(v,i){
var haystack = v[name];
var needle = new RegExp(value);
// check for string in haystack
// return the matched item if true, or null otherwise
return needle.test(haystack) ? v : null;
});
return array;
}
A native .map() function:
map = function(array, mapFunction) {
var newArray = new Array(array.length);
for(var i = 0; i < array.length; i++) {
newArray[i] = mapFunction(array[i]);
}
return newArray;
}
Your object:
(skimmed from your posted abject):
myObject = {
name : "soccer",
elems : [
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
},
{
name : "basketball",
elems : [
{name : "Dallas Mavericks"}
]
}
For usage:
(This will search your myObject.elems array for a 'name' matching 'FC')
var matched = myObject.elems.findValue('name', 'FC');
console.log(matched);
The result - check your console:
[Object, Object, findValue: function]
0: Object
name: "FC Barcelona"
__proto__: Object
1: Object
name: "Liverpool FC"
__proto__: Object
length: 2
__proto__: Array[0]
Try jOrder. http://github.com/danstocker/jorder
It's optimized for fast O(logn) search and sorting on large (thousands of rows) tables in JS.
As opposed to array iteration, which most of the answers here are based on, jOrder uses indexes to filter data. Just to give you an idea, free-text search on a 1000-row table completes about 100 times faster than iteration. The bigger the table, the better ratio you get.
However jOrder can't process the format of your sample data. But if you re-format it like this:
var teams =
[
{ sport : "soccer", team: "FC Barcelona" },
{ sport : "soccer", team: "Liverpool FC" },
{ sport : "basketball", team : "Dallas Mavericks"}
]
You can get the desired results by first setting up a jOrder table:
var table = jOrder(teams)
.index('teams', ['team'], { grouped: true, ordered: true, type: jOrder.text });
And then running a search on it:
var hits = table.where([{ team: 'FC' }], { mode: jOrder.startof });
And you'll get exactly the two rows you needed. That's it.
The straightforward way to do this is simply to iterate over every property of the object and apply a test function to them (in this case, value.contains("FC")).
If you want it to go faster, you'd either need to implement some kind of caching (which could be eagerly populated in the background ahead of any queries), or perhaps precalculate the result of various popular test functions.
You could do this with regular expressions performed against a serialized JSON string:
var jsonString = "[{ name : \"soccer\", elems : [ {name : \"FC Barcelona\"}"
+", {name : \"Liverpool FC\"}]},{name : \"basketball\",elems : ["
+"{name : \"Dallas Mavericks\"} ]}]";
var pattern = /\s*([\w\d_]+)\s*:\s*((\"[^\"]*(your pattern here)[^\"]*\")|(\'[^\']*(your pattern here)[^\']*\'))\s*/g;
var foundItems = [];
var match;
while(match = pattern.exec(jsonString)){
foundItems.push(match[0]);
}
var foundJSON = "[{" + foundItems.join("}, {") + "}]";
var foundArray = eval(foundJSON);
I haven't tested the loop part of this, but the Regex seems to be working well for me with simple tests in firebug.
In regards to AngularJS, you can do this:
var item = "scope-ng-model";
(angular.element('form[name="myForm"]').scope())[item] = newVal;

Categories