select arrays out of a Javascript object - javascript

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?

Related

How do I add key:value pair in an order in javascript

I need to add key:value into an object.
var a = {}
a['first'] = [a,bunch,of,stuff]
a['eight'] = [another,bunch,of,stuff]
a['two'] = [more,stuff]
but now variable 'a' contains
{eight: [a,bunch,of,stuff],first: [another,bunch,of,stuff],two: [more,stuff]}
while what I wanted was
{first: [another,bunch,of,stuff], eight: [a,bunch,of,stuff],two:[more,stuff]}
I'm guessing the order is based on the alphabetical order of the keys. This is a problem, because I want to display the data into hbs using {#each model as |key value|} in the same order as I wanted it.
in most languages lists have order where objects and sets do not. objects are key value and have no order.
in js arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays
this basically means you can place data anywhere in array, and it will be in order in the array
var idx = [];
idx[0] = 'hello';
idx[999] = 'world';
so what i believe you're looking for is
var listOfThings = [];
listOfThings.push({ 'first': [ 'things' ] })
listOfThings.push({ 'eight': [ 'stuff' ] })
listOfThings.push({ 'two': [ 'more'. 'things' ] })
then you can loop over accessing the key and value for each object.
Example you have an object, which is already have 2 key pairs, a1 & b2. Then you would like to add k3, you can use this method :
let objData = [{"a1":10,"b2":20},{"b2":11,"a1":23}]
Object.keys(objData).map(
function (object) {
// add k3
objData[object]["k3"] = "foo"
})
Then if you want to sort the keys alphabetically, use this method :
function orderKeyAlfAsc(obj) {
let data = []
for (var i in obj)
data.push(Object.keys(obj[i]).sort().reduce((r, k) => (r[k] = obj[i][k], r), {}))
return data
}
let orderedData = orderKeyAlfAsc(objData)

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Which JS methods/libs to extract selected arrays and properties from a complex object

Let's say I have an array of JSON objects such as below:
{
title: 'foo',
alias: 'bam',
innerArr: [{
name:'foo',
id:'123',
options: [{id:3,title:'boo',values:[{id:5,name:'Boo'}] }]
}]
}
Is there any library or shorthand method that doesn't involve writing nested for loops that will iterate over a collection of such objects and create a new array, but only with the properties I want projected/selected. So, say I want a copy of this array, but don't want the property title and the nested options[{}] array in the target array. So this new array will have all the same data, but each member of the array will now not have those two objects. Something I can overload like so perhaps var newarr = method({}, sourceArray, {title, options });
Just create a clone object (or you could work on initial object) and delete what you want, e.g:
var newObj = JSON.parse(JSON.stringify(o));
delete newObj.title;
newObj.innerArr.forEach(function(_o, i){delete _o.options});
console.log(newObj);
If you have to deal with specific nested objects as Date, use jQuery extend to clone object.
var newObj = $.extend({}, oldObject);
Let's say I have an array of JSON objects
For an array of object:
var newArr = JSON.parse(JSON.stringify(arr));
newArr.forEach(function (_o, i) {
delete _o.title;
_o.innerArr.forEach(function (__o, i) {
delete __o.options
});
});
console.log(newArr);
-jsFiddle-
EDIT: now i guess some library as prototypejs would have some handful methods but i don't know this library.

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.

Mootools convert Hash to array

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

Categories

Resources