Is their any way to create mutidimensional arrays in Javascript with Non Numeric Idex?
like the structure
optionList[0]['id'] = "equals";
optionList[0]['name'] = "Equals";
optionList[1]['id'] = "not_equals_str";
optionList[1]['name'] = "Does Not Equal";
optionList[2]['id'] = "contains";
optionList[2]['name'] = "Contains";
Yes, at least some kind of object that will do what you want even if it's not really a "multidimensional array".
You create a mododimensionnal array.
And you populate it with simple javascript objects, which you can consider as some kind of maps for many purposes.
var optionList = [];
optionList.push({});
optionList[0]['id'] = "equals";
...
You can create it in one go :
var optionList = [
{id:"equals", name:"Equals"},
...
];
In JavaScript you should use objects as arrays with non numeric indices. So your structure will look as follows:
var optionList = [
{
id : "equals",
name : "Equals"
},
{
id : "not_equals_str",
name : "Does Not Equal"
},
{
id : "contains",
name : "Contains"
}
];
Those are arrays that contain objects. It would look like this:
var optionList = [
{},
{},
{}
];
Yes You can always have nesting of Objects.
optionList = [{
id: "equals",
name: "Equals"
},{
id: "not_equals_str",
name: "Does not Equal"
},{
id: "contains",
name: "Contains"
}]
Yes. You have to define an empty array and then push those details as object into it.
var optionList = [];
optionList.push({id: 'equals', name: 'equals'});
optionList.push({id: 'not_equals_str', name: 'Does Not Equal'});
Hope this helps.
Related
Need to find whether array object If exist in array. I have one arrayObject and array collections.
my code:
var array = [
{
id:0,
item_fields:{text: "stack", type: "2", options: null},
item_id:"540551c1-1744-4f09-920f-75350ba23cb6",
item_parent:"e50b00d5-8c3e-449e-92ba-41ff9d46babe",
sequence:-1
},
{
id:0,
item_field_type:"multiChoiceNumeric",
item_fields:{text: "overflow", type: "RangeNumeric", options: null},
item_id:"1bacc69f-d8c9-4107-af60-295f8994d249",
item_parent:"e50b00d5-8c3e-449e-92ba-41ff9d46babe",
sequence:-1
}];
var arrObj =
{
id:0,
item_field_type:"multiChoiceNumeric",
item_fields:{text: "stack", type: "2", options: null},
item_id:"540551c1",
item_parent:"e50b00d5",
sequence:-1
}
This query returns false:
array.some(function(element){return element == arrObj})
This query returns -1 (If not found):
jQuery.inArray(arrObj,array)
Why do both queries return not found results? What should I do to get a correct result?
In JavaScript, variable assignment to Object is similar to a pointer in C; the variable is a reference to the memory location of the Object, not the Object and its contents itself.
var x = {};
var y = {};
x === y;
// false
Rather than compare equality of references to objects, you can update the callback in array.some() to check for deep equality, but this can get cumbersome.
It may be better to compare a key in the objects that you know will be unique, such as "item_id":
array.some(function(element) {
return element.item_id === arrObj.item_id;
});
i want to get complete index of a complex object inside of a multiple dimensional array.
E.g. i have the following array.
var arr = [
{
name: "zero", children: null
},
{
name: "one", children: [
{
name: "one_zero", children: [{ name: "one_zero_zero", children: null }]
}
]
}
];
I want to get of the object with the name "one_zero_zero". It should be of indexes 1_0_0.
I hope you guys can help me with this problem.
Best regards,
var newarr =[];
var index = "";
function findmeinarr(s,arr){
for(let i in arr){
var name = "";
var flag = false;
name=arr[i].name
if(name==s){
index+=i;flag=true;
}
if(arr[i].children!=null){
newarr = arr[i].children;
index+=i+"-";
}
}
if(flag)console.log(index);
else findmeinarr(s,newarr);
}
Here is the working snippet for this :
https://codepen.io/sidhanshu28/pen/xzEyqZ
I am using recursive call here. Let me know if I can help more. Please mark it as solution, if it works for you.
I have this array :
var hemicycle = {
Group1 : [{
GroupName : "Les bests",
Member1 : [{
Name : "Loris Plasson",
Seat : 4,
Vignette : "PhotoURL"
}],
Member2 : [{
Name : "Anne-Sophie",
Seat : 3,
Vignette : "PhotoURL"
}]
}]
I want to push the object Member1 or Member2 on another object depending of the Seat value.
To do that I think I need to "search" for the Seat value with a for loop and retrieve the object, but all the examples I found on StackOverflow were with simple arrays like this :
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
With those simple arrays they are able to use something like a for loop with array[i].
But in my case I really don't know what to do...
UPDATE : What I want : The Member object which include the corresponding Seat value searched. Then I push the Member object to another object.
Thanks for any help.
The data structure that you use doesn't reflect what you are trying to convey, and in addition is very heard to traverse.
I suggest creating an array of groups. Each group is an object, that has the members property, which is an array of member objects:
[{
"GroupName": "Les bests",
"members": [{
"Name": "Loris Plasson",
"Seat": 4,
"Vignette": "PhotoURL"
},
{
"Name": "Anne-Sophie",
"Seat": 3,
"Vignette": "PhotoURL"
}
]
}]
Using this structure, you find a member using 2 for loops - one to iterate the groups, and the other to iterate the members of each group. Once a member is found, the function returns the member's object immediately. If not undefined is returned:
var groups = [{"GroupName":"Les bests","members":[{"Name":"Loris Plasson","Seat":4,"Vignette":"PhotoURL"},{"Name":"Anne-Sophie","Seat":3,"Vignette":"PhotoURL"}]}];
var seatNum = 4;
function findMember(seatNum) {
var members;
for(var i = 0; i < groups.length; i++) {
members = groups[i].members;
for(var j = 0; j < members.length; j++) {
if(members[j].Seat = seatNum) {
return members[j];
}
}
}
}
var member = findMember(seatNum);
console.log(member);
I have a fairly complex array generated from Google's natural language API. I feed it a paragraph of text and out comes lots of language information regarding such paragraph.
My end goal is to find "key words" from this paragraph, so, to achieve this I want to put all the "entities" into a flat array, count the duplicates, and then consider words with the highest amount of duplicates to be "key words". If it doesn't find any then I'll cherry pick words from entities I consider most significant.
I already know the entities that could exist:
var entities = [
'art',
'events',
'goods',
'organizations',
'other',
'people',
'places',
'unknown'
];
Here is an example structure of the array I'm working with.
input = [
{
language: {
entities: {
people: [
{
name: "Paul",
type: "Person",
},
{
name: "Paul",
type: "Person",
},
],
goods: [
{
name: "car",
type: "Consumer_good",
}
], //etc
}
}
}
];
output = ["Paul", "Paul", "car"...];
My question is - what is the best way to convert my initial array into a flat array to then find the duplicates without using a whole bunch of FOR loops?
There is no way around loops or array functions if you work with dynamic input data.
You can access all the values using this format:
input[0]["language"]["entities"]["people"][0].name
input = [
{
language: {
entities: {
people: [
{
name: "Paul",
type: "Person",
},
{
name: "Paul",
type: "Person",
},
],
goods: [
{
name: "car",
type: "Consumer_good",
}
], //etc
}
}
}
];
console.log(input[0]["language"]["entities"]["people"][0].name);
Then you could do something like this:
for (var entry in input[0]["language"]["entities"]) {
console.log(entry);
}
OR, if I understood you wrong,
You can use this to turn the javascript Object into an array using this (requires jquery):
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array[0][0]);
console.log(array[0]);
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This will output
1
[1, 2, 3]
[[1,2,3],[4,5,6]]
You could iterate through input.language.entities in a recursive way and collect all the .name properties into an array. Then you have only one for loop :-).
After doing that, you can iterate through it to find the duplicates. If you sort it alphabetical before it is easier (if two or more consecutive entries are equal, there are duplicates).
But it could be a bit dangerous if google changes the api or if it delivers crap data because of a malfunction.
Isn't input.language.entities already flat enough to work with it?
I ended up doing something like this. It's not pretty but it gets the job done.
var result = [];
var known_entities = ['art','events','goods','organizations','other','people','places','unknown'];
for(i=0; i < known_entities.length; i++){
var entity = known_entities[i];
if(language.entities[entity]){
for(var j in language.entities[entity]){
var word = language.entities[entity][j].name
result.key_words.push(word);
}
}
}
I want to create an object with an array property which looks like this:
var arrayOfUsers = {
id: "some user id",
username : "some names",
roles : [array with roles]
}
And i would like to access an element by id, something like, arrayOfUsers['some id']['roles'];
I am new to json. I've tried different ways, but always ended up with bunch of errors.
First, this is a JavaScript object. JSON is a string representation of JavaScript objects.
Second, it's important to know the difference between an object and an array. In general, consider Objects to be defined with curly braces { } and Arrays with braces [ ]
Values in Arrays are accessed by their index with the arr[index] syntax while objects use obj[key] syntax to access the value assigned to some key on the object.
For your scenario, I'd avoid using arrays, because you want to be able to access objects by key, not by index.
var users = {
"some user id": {
username : "some names",
roles : {
"some role id": {
name: "role name"
}
}
}
};
In reality, this isn't a very effective data structure, because you'd likely want to deal with arrays for looping, rendering, etc, but to answer your question about being able to index by the Id of user and role, this is how your data would have to be structured.
Here is how you declare:
var currentUser,
currentRole,
arrayOfUsers = {
id: 1,
username: "Sample Value",
roles: [{
roleId: 1,
name: "Admin"
},
{
roleId: 2,
name: "Cashier"
}]
};
This is how you access it:
for (var i = arrayOfUsers.length; i--;) {
currentUser = arrayOfUsers[i];
for (var x = currentUser.roles.length; x--;) {
currentRole = currentUser.roles[x];
console.log("ID=" + currentRole.id + "Name=" + currentRole.name);
}
}
First, you have to make difference between array which defined by [], and Objects, by {}.
If you want to make an array of JSON, you can do the following :
var arrayRoles = [{
idRole: 1,
type: 'admin'
}, {
idRole: 2,
type: 'user'
}];
var userArray = [{
id: 1,
username: 'toto',
roles: arrayRoles
}, {
id: 2,
username: 'titi',
roles: arrayRoles
}, {
id: 3,
username: 'toto',
roles: arrayRoles
}];
Then, if you want to iterate over all your data, you can do it by using forEach loop, which tends to be more elegant :
userArray.forEach(function(elm){
//Our roles array
var roles = elm.roles;
//For all item in roles array
roles.forEach(function(value){
//display type of role, for example.
console.log(value.type);
});
});
But if you want to search a specific item in your JSON array, you can use filter method, by using high order function.
function filterBy(key, filter){
return function(elm){
return elm[key] === filter;
}
}
Then, you can apply this function to your filter, by passing specific field and value, and it will return an array of results :
var filtered = userArray.filter(filterBy('username', 'toto'));
//Display '1'
console.log(filtered[0].id);
//Display '3'
console.log(filtered[1].id);