Find values in multidimensional array - javascript

Assume I have an array in my script and it's made up like this:
var detail= {};
detail['i100']=new Array()
detail['i100']['ID 4564']= 'John'
detail['i100']['ID 4899']= 'Paul'
detail['i100']['ID 9877']= 'Andy'
detail['i100']['ID 1233']= 'Evan'
detail['i25'] = new Array()
detail['i25']['ID 89866']= 'Paul s'
detail['i25']['ID 87866']= 'Paul'
I then use this script to get the values of the first part of the array:
$.each(detail, function(vehicle) {
console.log( vehicle )
});
This gives me two results as expected (i100 and i25), What I want to do however is, by using the reference vehicle, get all the names and values of the second dimension –
i.e. by using i25 I want to return ID 89866 and ID 87866. I have tried children(), but it is just not working. Does anyone have any advice, please ?

You need to run another each on the 2nd dimension.
$.each(detail, function(index,value){
$.each(value, function(i,v) {
console.log(v);
});
});
or if you want to specifically call one item, pass in the value name:
function getByName(name){
$.each(detail[name], function(i,v){
console.log(v);
});
}

Related

Get value from javascript nested array

I am new in coding JavaScript. So far I know how to set and get values from a multi array, but with this one I cannot find the right way to do it.
I am trying to get the email value from this array:
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
I tried
JSON.parse(__ar.tag.email)
document.write(__ar[2][2])
Everything I tried so far I got either undefined or tag[object, object].
What's the easiest way to get it?
The email property is located on the second element of the array (that is index 1 of the zero based indexed array). So, to access it, you also need to access the second object of the element (again index 1) and then .email is at your hand:
document.write(__arr[1][1].email);
Assuming that you only push those two values, your array looks like the following:
[
['id' ,'12541'],
['tag', {"sub":false,"email":"email#email.com"}]
]
Means, that when you access it using __arr.tag.email will result in an undefined error, because it's an array not an object.
Therefore what you could do is, if you don't know exactly the index:
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
for (var i = 0; i < __arr.length; i++){
if(__arr[i][0] === 'tag'){
console.log(__arr[i][1].email);
break;
}
}
so you have an array as __arr, the first element you are pushing is id which is an array second array is having your email id.
so you can access as shown below.
I hope this will solve your issue
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log("email id =>", __arr[1][1].email)
I hope you know array is starting from its index that's base value is 0. in your code there is no such element which is available in index 2.
document.write(__ar[2][2]) //
I know lots of answer is given here, but i just want to tell you even you are pushing value in "__arr" i.e an array of array. so every element is storing in its index value.
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log(__arr[0]) //return you ["id", "12541"]
console.log(__arr[1]) //return you ["tag", {sub: false, email: "email#email.com"}]
again you can see inside of your "__arr" there is a an array element
console.log(__arr[0][0]) //return you "id"
console.log(__arr[0][1]) //return you "12541"
console.log(__arr[1][0]) //return you "tag"
console.log(__arr[1][1]) //return you {sub: false, email: "email#email.com"}
and here what you want i.e.
console.log(__arr[1][1].sub) //return you false
console.log(__arr[1][1].email) //return you "email#email.com"
A dynamic way to do it (with level of 2 nested levels).
Basically, I used two nested loops and aggregated the emails into a list.
let __arr = []
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
__arr.push(['tag2', {"sub":false,"email":"2222#email.com"}]);
const emails = __arr.reduce((res, items) => {
items.forEach(elem => {
if (elem.email) res.push(elem.email)
})
return res
},[])
console.log(emails)
// [ 'email#email.com', '2222#email.com' ]

Append data acquired from JSON to a Raphael object

Solved the question on my own, see answer
Using jQuery 3.2.1 and Raphael 2.1.1, if this matters
In my Raphael .js I first create some objects without any data and push them into an array, e. g. (.attr omitted):
var objarr = [];
var obj1 = rsr.path("M ... z");
objarr.push(obj1);
After this, I want to take data from a JSON file (an array named "regions" of multiple entries that consist of multiple key-value pairs (validated through JSONLint) and append it as data by id. It looks like this:
{
"regions": [{
"id": "0",
"var1": "foo1",
"var2": "bar1",
},
{
"id": "1",
"var1": "foo2",
"var2": "bar2",
},
// And so on for every object
]
}
I use the following code (localhost is used because otherwise I get a cross-access error:
for (var i = 0; i < objarr.length; i++)
{
var jq = $.getJSON("http://localhost:8000/data.json",{id: +i},function(t){
console.log( "success" );
})
.done(function(objdata){
console.log("success2");
$.each(objdata.regions, function(key, val){
objarr[i].data(key,val);
});
})
.fail(function(t){
console.log("error");
})
.always(function(t){
console.log("complete");
});
}
The console gives me both successes, but after this I get an error "Cannot read property 'data' of undefined". alert(key) and alert(val) give 0 and [object Object] respectively for every call. I tried adding the following to .done:
var items = [];
$.each(objdata.regions, function(key, val){
items.push("id" + key + ":" + val);
console.log(items);
});
The result was a string that went ["id0:[object Object]"],["id0:[object Object]", "id1:[object Object]"] and so on until it had objarr.length ids, repeating the needed amount of times. If I add [i] to objdata.regions, I get no console messages about items[] content at all.
I also found two somewhat closely related questions ("1" and "2"), checked the jQuery documentation for .getJSON(); and Raphael documentation for Element.data();. I've tried the following to check validity of my calls:
console.log(objdata) in the beginning of .done -- returns full base object of JSON data
console.log(objdata.regions) in the beginning of .done -- returns array of objects of JSON data
console.log(objdata.regions[i]) in the beginning of .done -- returns undefined
console.log(objdata.regions[0]) in the beginning of .done -- returns first object (works for every object)
I've used objdata.regions[0] in the snippet with items[] and the adding seems to work properly (console shows the keys and values being added to the array). However, it still doesn't work with objarr[i].data(key,val) (as well as ""+key and "$key").
I have two questions:
1. How do I acquire the key-value pairs properly while looping?
2. How do I append these pairs as data to a Raphael object?
I moved the for loop inside .done() and everything is appended successfully:
.done(function(objdata){
for (var i = 0; i < objarr.length; i++)
{
console.log("success2");
$.each(objdata.regions[i],function(key, val){
objarr[i].data(key, val);
});
}
})

What is the equivalent of Array.prototype.map() for objects in JavaScript

I am trying to take some some objects from an original object into an array variable.
console.log("news len", news["articles"].length); // this comes out to 9
for(var a in news["articles"]) {
var results = [];
results.push({
title:news["articles"][a]["title"],
subtitle: news["articles"][a]["description"],
item_url:news["articles"][a]["title"],
image_url:news["articles"][a]["urlToImage"],
});
}
console.log("results len",results.length); //only contains one entry
Is there another way to accomplish this, and if not what am I doing wrong?
Using Node js if that helps any.
You could use map directly and return an object in the callback for a new array
var results = news.articles.map(function (a) {
return {
title: a.title,
subtitle: a.description,
item_url: a.title,
image_url: a.urlToImage
};
};
The main problem is that each iteration of your loop re-sets results to an empty array:
var results=[];
If you move that statement before your loop, you will get something closer to what you want.
That said, it looks like news["articles"] already is an array, so you can probably just use Array.prototype.map?
var results = [];
news["articles"].map(function(val,idx){
results.push({
title: val["title"],
//etc
}
});

get element in array item ajax

I have a function writen in ajax that return a set of value:
$.each(data.dataa, function (i,item) {
$.each(item, function (index, dat) {
$str+=dat;
})
$ulSub.append( '<li id="'+item.id +'" class="ui-widget-content">' +$str+'</li>');
});
Each item has two attribute: the id and the lastname,
the value of each $str is a concatenation of the id and the lastname, but I want just the lastname not the id. I used the function item[2] but it's not working.
the result of my code is shwon as follow
What I want is just get the value of the lasname. I know that I should use item.lastname, but I want to ask if there are other methods to get the value of the lastname because the second attribute (lastname) is a variable.
Well, your case is quite simple, you always have an object with 2 properties: id and an unknown property. As objects do not have a defined order, you can´t assume that the field you want is always in second position
One way is to iterate the keys, and pick the one that is not equal to id:
for(var key in item){
if(key != 'id'){
$str+= item[key]
}
}
A similar way is to pick the object keys, and filter out the id one, then access the object with that key:
$str+= item[Object.keys(item).filter(function(k){return k != 'id'})[0]]
If you know the possible values of the key, another way would be:
var possibleKeys = ['lastname', 'name', 'adress', 'phonenumber']
for(var key in item){
if(possibleKeys.indexOf(key) != -1){ // if its a valid key, append the value
$str+= item[key]
}
}
In your case, the first option is probably the best, but there are mutiple ways to do it

Display elements in my 2d Array in Javascript

I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com

Categories