I have an object array which looks like:
Object {0: "Ma. Jessa Martinez", 1: "Edwin Cuevas", 2: "Gerum Generol", 3: "Roy delos Reyes", 4: "Hannah Montecillo", 5: "Ralph Turla", 6: "Edralyn Danabar", 7: "Angelo Sto Domingo", 8: "Rhina Dela Cruz", 9: "Ricardo Camara", 10: "Joene Floresca"}
And I want to convert in array like:
[[0,"Ma. Jessa Martinez"],[1,"Edwin Cuevas"],[2,"Gerum Generol"], and so on]
I tried using
var myobj_array= $.map(ticks, function(value, index) {
return [value];
});
But it only return the values with no keys:
["Ma. Jessa Martinez", "Edwin Cuevas", "Gerum Generol", "Roy delos Reyes", "Hannah Montecillo", "Ralph Turla", "Edralyn Danabar", "Angelo Sto Domingo", "Rhina Dela Cruz", "Ricardo Camara", "Joene Floresca"]
Is there other way? I've search already in google I can't find a similar thing.
EDIT To be clear where my object array came from, I added this for reference. It came from an ajax request and already sorted:
var ticks = {};
$.each(result, function(key,value) {
ticks[key] = value.name;
});
Use instead :
var myobj_array= $.map(ticks, function(value, index) {
return [[index,value]];
});
console.log(myobj_array);
#PinkTurtle point is important, because we may pay attention to the performance or use vanillajs instead jQuery.
However if the object structure use instead :
{80: "Ma. Jessa Martinez", 12: "Edwin Cuevas"}
and we process with only the index (and we retrieve it like arr[80] would be undefined, only if we use arr[0] would work, but the index of the user is not 0 , is 80).
Or just use normal js:
var arr = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
arr.push([i, obj[i]]);
}
}
You may create a new Javascript object and return as follow:
var myobj_array= $.map(ticks, function(value, index) {
Var obj=[[index,value]];
return obj;
});
Related
So I basically have a gradebook that is a .csv file and is formatted like this
name, grade
name, grade
I am looking for the best way to split my array so that I can access each independently but they are still related to each other.
function handleFileLoad(event){
var baseText = event.target.result;
var splitString = baseText.split("\r\n");
console.log(splitString)
}
This is my current code so it currently splits the original text into the array properly but the output is like this
0: "Name,Percent"
1: "Eddie,65.95"
2: "Alice,56.98"
3: "Delmar ,96.1"
4: "Edmund ,78.62"
when I want it like
0: "Name" "Percent"
1: "Eddie" "65.95"
2: "Alice" "56.98"
3: "Delmar" "96.1"
4: "Edmund" "78.62"
Add this code:
for(let i = 0; i < splitString.length; i++){
splitString[i] = splitString[i].split(",")
}
As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data.
exact_match : {104}
match_4 : {104, 103}
match_2 : {104, 103, 68}
How can I "trim" or remove the duplicate objects based on previous ones? something like:
exact_match : {104}
match_4 : {103}
match_2 : {68}
I tried _.difference but did not work (Maybe because it is for arrays not objects?):
var exact_match = data.exact_match,
match_four_digits = _.difference(data.match_4, data.exact_match),
match_two_digits = _.difference(data.match_2, data.exact_match, data.match_4),
Any help would be appreciated :)
Update
I need that the returned value has the same object data instead of a new array :)
It looks like you want to diff keys (or rather, it'd be efficient to — _.keys)
_.difference(
_.keys({104: 1, 102: 3, 101: 0}), // ["104", "102", "101"]
_.keys({104: 1, 102: 3}) // ["104", "102"]
)
// [ "101" ]
Or, you could always convert your object to an array of pairs if you want to compare within the objects too (_.pairs):
_.difference(
_.pairs({104: 1, 102: 3, 101: 0}), // [["104",1], ["102",3], ["101",0]]
_.pairs({104: 1, 102: 2}) // [["104",1], ["102",2]]
)
// [["102", 3], ["101", 0]]
I would create a map called unique, e.g. var unique = {}; and then iterate over each key in your data and check if it's in unique. If it is in unique, delete the entry associated with that key, thus removing duplicates.
You could pull this check out as an alreadyFound method:
var alreadyFound = function (key) {
if (!(key in unique)) {
unique[key] = true;
return false;
}
return true;
};
Then iterate over your data and check alreadyFound(key) for key in your data, and delete the key if alreadyFound(key) returns true.
You could go messing with lodash/underscore methods but those might be inefficient depending on how you use them (and how they're implemented) and this should operate in linear time.
It looks like for your specific use case the full solution would be something like:
var unique = {};
// Assume I copy and pasted alreadyFound here
var alreadyFound = ...;
for (var object in data) {
// Iterate through ids in each object in data
for (var id in object) {
// Remove this entry if it's already found
if (alreadyFound(id)) {
delete object[id];
}
}
}
Thanks guys for the answers, I really appreciate your time.
I searched further and found this post by Lodash developer that helped me came up with this snippet;
var data = {
exact_match: {
104: {
supplier_id: 104
}
},
match_four_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
}
},
match_two_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
},
103: {
supplier_id: 103
},
999: {
supplier_id: 999
}
}
};
var arr_match_four_digits = _.difference(_.keys(data.match_four_digits), _.keys(data.exact_match));
var arr_match_two_digits = _.difference(_.keys(data.match_two_digits), _.keys(data.match_four_digits), _.keys(data.exact_match));
$('#output1').html(JSON.stringify(data));
$('#output2').html(JSON.stringify(_.pick(data.match_four_digits, arr_match_four_digits)));
$('#output3').html(JSON.stringify(_.pick(data.match_two_digits, arr_match_two_digits)));
<script src="https://cdn.rawgit.com/lodash/lodash/3.3.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
data
<pre><code><div id="output1"></div></code></pre>
arr_match_four_digits
<pre><code><div id="output2"></div></code></pre>
match_two_digits
<pre><code><div id="output3"></div></code></pre>
In a nutshell I am making a REST call to my database and getting a list of ingredients back. The JSON looks like:
[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},
{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},
{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]
What I want to do is transform this into a useful array that is organized as:
Milk
2%Skim/Fat Free
Cheesechedder
In addition to it being ordered like that, I want to maintain the ID associated with each item. So cheese would have "2" and chedder would have "3".
I have been able to feed the unique values of Milk and Cheese into an array but I am not sure how to proceed. Advise would be appreciated!
Here's what I have so far:
$.ajax({
url: "../api/IngredientChoices",
contentType: "json",
success: function (data) {
var _subCategories = {};
var _mainCategories = [];
$.each(data, function (index, item) {
if ($.inArray(item.MainName, _mainCategories) === -1) {
_mainCategories.push(item.MainName);
}
});
$.each(_mainCategories, function () {
alert(this);
});
}
});
Detailed working answer. The data is added to an associative array.
obj = JSON.parse(data);
console.log(obj);
d = {}
$.each(obj, function (index, item) {
if (!(item.MainItemID in d)) {
d[item.MainItemID] = [];
d[item.MainItemID][0] = item.MainName;
d[item.MainItemID][1] = {}
}
d[item.MainItemID][1][item.SubItemID] = item.SubName;
});
console.log(d);
Output:
Object {1: Array[2], 2: Array[2]}
1: Array[2]
0: "Milk"
1: "2%"
2: "Skim/Fat Free"
2: Array[2]
0: "Cheese"
3: "Chedder"
You might want to edit your question. The 'useful' array you want is actually not an array. You might want this :
[
{
name : 'Milk',
subTypes : [ '2%', 'Fat Free'],
},
{
name : 'Cheese',
subTypes : [ 'Cheddar' ],
}
]
jsfiddle example
var data = [{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},
{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},
{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}];
var ordered = {};
for(var i = data.length; i--;) {
var mainItemID = data[i].MainItemID;
if(!ordered[mainItemID]) {
ordered[mainItemID] = {};
ordered[mainItemID].MainName = data[i].MainName;
ordered[mainItemID].MainItemID = mainItemID;
}
ordered[mainItemID][data[i].SubItemID] = data[i];
}
console.log(ordered);
And you can have a array with your object collection, that way you will be able to sort it:
var dataArray = [];
for(var k in ordered) {
dataArray.push(ordered[k]);
}
console.log(dataArray);
If you plan more complex data parsing, or manipulation, I would recommend some model/collection framework, like: Backbonejs, SpineJS, or even use webSQL or IndexedDB.
I'm looking for the best solution here, i've got an idea but thinking it could be done prettier.
I'm making an simple weather application. And i'm using Yahoo Weather api were they have got codes for weather conditions.
Depending on the condition i'm giving a code. Now, there are 50 codes and i've categorised them into 5 categories. In my case ex. my categori Snow contains 15 of Yahoo's condition codes.
Well, if you got a better idea (which i bet there is) be free to suggest.
My thought is to return the matching value from a set of arrays, but not shure how to do it.
My code now looks like this:
function getCondition(code) {
var snow = [1, 2, 3],
sun = [4, 5, 6];
}
What i need is the variable name that contains the matching number of the code?
I've made a JS-Fiddle
http://jsfiddle.net/BH8r6/
The fastest lookup (translating a Yahoo code to your label) is to use the code as array key (if they are sequential).
var weather = [];
weather[0] = "no_weather";
weather[1] = "snow";
weather[2] = "snow";
weather[3] = "snow";
weather[4] = "sun";
weather[5] = "sun";
weather[6] = "sun";
function getCondition(code) {
return weather[code];
}
Why dont you try an associative array when your key is your variable name and your values is the corresponding code for the variable name, thus your code will be something like this:
var myCodeArray=[];
myCodeArray["snow"]=[1, 2, 3];
myCodeArray["sun"] = [4, 5, 6];
now your method getCondition will be
function getCondition(code)
{
for(var definedCodeName in myCodeArray)
{
if(myCodeArray.hasOwnProperty(definedCodeName))
{
var array=myCodeArray[definedCodeName ];
for(var i=0;i<array.length;i++)
{
if(array[i]==code){
return definedCodeName ;}
}
}
}
return "Not found";
}
Demo
Why to complicate everything?! Just use 'switch' :
function getCondition(code) {
switch( code ){
case 1:
case 2:
case 4:
case 6:
return "snow";
case 3:
case 8:
case 9:
return "sun";
case 5:
case 7:
case 10:
return "cloudy";
}
return "none";
}
I have an array like the following
var data = [
["1"," 101_30.1.101_34","0.0200112629","mm/s","[OK]"],
["1"," 101_30.1.101_35","0.0146548533","mm/s","[OK]"],
["1"," 101_30.1.101_45","0.0146548533","mm/s","[OK]"],
["1"," 101_42.2.101_43","0.0101406257","mm/s","[OK]"],
["2"," 102_17.3.102_38","5.1719756","mm/s","[WA]"],
["2"," 102_17.3.102_39","3.5886707","mm/s","[WA]"],
["2"," 102_17.3.102_44","9.4615074E-4","mm/s","[OK]"],
["2"," 102_40.4.102_41","4.8159785","mm/s","[OK]"],
["3"," 204_15","3.8374166","mA","[OK]"],
["4"," 501_11","1027.5156","RPM","[WA]"]
]
What im trying to do is find how many unique array there are. Example 1=4,2=4,3=1,4=1
The data is coming from a database, so the number of arrays can always change.
Here is a simple jsfiddle of what im talking about JsFiddle
Try something like this:
var count = {};
$.each(data, function(){
var num = this[0]; // Get number
count[num] = count[num]+1 || 1; // Increment counter for each value
});
console.log(count); // {1: 4, 2: 4, 3: 1, 4: 1}