Mootools convert Hash to array - javascript

I have Hash obj:
var obj = {a,b,c,...};
obj = $H(obj);
I need to convert it to simple array
[a,b,c,..]
How can I do?
Thx.

Object.getValues(myObject) to get an Array of all values.
Object.getKeys(myObject) to get an Array of keys.
For 1.2 simply, Hash provides the same methods.
And don't use Objects {} to store lists like in your example. Arrays are for lists, Objects are for associative arrays.
EDIT:
Since version 1.3 Object.getValues and Object.getKeys has been deprecated and replaced by Object.keys resp Object.values.

since you use $H I am assuming older ver of mootools, 1.2.x since it got deprecated in 1.3 in favour of the new Object. construct
The hash had a .each method:
var Hobj = $H({
tool: "bar",
ghost: "goblin"
});
var arr = [];
Hobj.each(function(value, key) {
arr.push(value); // what to do with key?
});
console.log(arr);
an alternative that grabs the complete objects with their keys but not as array keys:
Hobj.each(function(value, key) {
var obj = {};
obj[key] = value;
arr.push(obj);
});

Assuming you want the values in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(obj[prop]);
}
}
If you want the property names to be in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(prop);
}
}
the hasOwnProperty call is important because it will filter out inherited functions and private members of the mooTools hash class that you don't probably want in your resulting array

Related

Javascript: Map iterate object keys and values

Trying to get both key and value using the following script
jsonData = {"jurisdiction":"SCPB - LON","firstName":"David Dynamic"}
var keys = Object.keys(jsonData).map(function(keys, values) {
logInfo(jsonData[keys], jsonData[values]);
});
returns just the values:
2022-08-30 18:29:49 David Dynamic undefined
2022-08-30 18:29:49 SCPB - LON undefined
How can I get both? the js engine is spiderMonkey 1.8
Object.keys(jsonData).forEach(function(key) {
logInfo(key, jsonData[key]);
});
Object.keys documentation
Or as suggested by Kondrak Linkowski:
Object.entries(jsonData).forEach(([key, value]) => logInfo(key, value))
You likely want to use Object.entries to get the keys and values of the object.
If you want to do it with Object.keys, as in your example, you can modify it like this: (logging the key, and the value at this key)
const jsonData = {
foo: 'bar',
fizz: 'fuzz',
}
const logInfo = console.log
var keys = Object.keys(jsonData).map(function(key) {
logInfo(key, jsonData[key]);
});

get key and value of array via underscore each

I would like to loop through an array and get the key and value of it. This is what I'm doing, but I don't get any output. What am I doing wrong?
let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
You are using array and adding a property to it which is not valid .Use object for it
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
_.each iterates through the indices of the array. You are adding a non-numeric property to the array object. Your array is empty and _.each callback is not executed. It seems you want to use a regular object ({}) and not an array:
let regexes = {};
Now _.each should iterate through the object own (by using hasOwnProperty method) properties.
You are assigning a property to the array. Lodash is attempting to iterate through the numeric indices of the array, but there are none. Change the array to an object and Lodash will iterate through its enumerable properties:
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.forEach(regexes, function(regex, key) {
console.log(regex, key);
});
Alternatively, if using an array is necessary, simply push the value onto it:
let regexes = [];
regexes.push(/([^.]+)[.\s]*/g);
_.forEach(regexes, function(regex, i) {
console.log(regex, i);
});

Sort javascript key/value pairs inside object

I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.

Convert array to Object by JSON.parse

var arr=[];
arr['first']='val1';
arr['second']='val2';
var json=JSON.stringify(arr);
var obj=JSON.parse(json); //obj is array
Can I return object {"first":"val1","second":"val2"} ?
P.S.: I read Convert Array to Object topic
I'm interested in this way of the function
If somebody has abused arrays like that, JSON does not help you. It will only serialize the numeric indices of Array objects, nothing else. Copy the properties by hand:
var obj = {};
for (var prop in arr)
if (arr.hasOwnProperty(prop)) // don't copy enumerables from Array.prototype
obj[prop] = arr[prop];
console.log(obj); // {"first":"val1","second":"val2"}
You shouldn't use an array to represent this:
Do this instead:
var obj = {first:"val1",second:"val2"};
Just define the object directly . Stringify and parsing is not necessary

select arrays out of a Javascript object

Having the following object obj:
{"Point Ref":[15629989,564646414,65494949],
"Effective Date":["2008-03-03","2010-12-14","2004-10-01"],
"Identifier":["EM","EM","SC"],"Status":["FI","SI","XC"]}"
I can select the first array with
obj["Point Ref"]
How can I select more of them? (like obj["Point Ref", "Identifier"]
This will iterate through all the first-level arrays in the object:
var obj = {"Point Ref":[15629989,564646414,65494949],
"Effective Date":["2008-03-03","2010-12-14","2004-10-01"],
"Identifier":["EM","EM","SC"],"Status":["FI","SI","XC"]};
for (var key in obj) {
if (obj[key] instanceof Array) {
console.log(obj[key]);
}
}
Then depending on what you actually want from this, you can either use a multi-dimensional array or concat them. For multidimensional you would do:
var multi = [];
....
multi.push(obj[key]);
For a single dimensional array you would do:
var single = [];
....
single = single.concat(obj[key]);
You can use concat() to build a new array from several existing ones:
var data = obj["Point Ref"].concat(obj["Identifier"]);
If you're looking for the call to return two values, like say in Matlab, it isnt supported.
Look here for alternate options on returning multiple values: Return multiple values in JavaScript?

Categories

Resources