Javascript: How can I transform an array? - javascript

I have this on a javascript var: (it's a http returned data, and I don't know if it's an array or string - (how can we see that?) - Update: using typeof returned "string", so it's a string.
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]
How can we pass/transform that, into something like this:
["gggg.fa","rarar.fa"]
?
Thanks a lot,
MEM

You can figure out if is a string or an already parsed object by checking the type of your variable, e.g.:
ajax('url', function (response) {
alert(typeof response);
});
You will now figure out if it's a "string" or an Array "object".
If it's a string, you can use the JSON.parse method as #alcuadrado suggest, otherwise you can simply use the array.
Several answers suggest the use of the for-in statement to iterate over the array elements, I would discourage you to use it for that.
The for-in statement should be used to enumerate over object properties, to iterate over Arrays or Array-like objects, use a sequential loop as #Ken Redler suggests.
You should really avoid for-in for this purpose because:
The order of enumeration is not guaranteed, properties may not be visited in the numeric order.
Enumerates also inherited properties.
You can also use the Array.prototype.map method to meet your requirements:
var response = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var array = response.map(function (item) { return item.nomeDominio; });
// ["gggg.fa", "rarar.fa"]

This question is strongly related with this one.
I would suggest reading my answer there, as it would really help; and with a little variation, it would just work:
var responseString = '[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]',
responseObject = JSON.parse(responseString),
nombresDeDominio = [];
for(var i in responseObject) {
nombresDeDominio.push(responseObject[i].nomeDominio)
}
Suerte!

Assuming your data always looks like that, you can do something like this:
var foo = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var newarr = [];
for ( var i=0,j=foo.length;i<j;i++ ) {
newarr.push( foo[i]['nomeDominio'] );
}
Here's a working fiddle.

function transform(array, f) {
var ret = [];
$.each(array, function(index) {
var v = f.call(this, index);
if(v) {
ret.push(v);
}
});
return ret;
}
var result = transform(
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}],
function() { return this.nomeDominio; }
);
alert(result.toString());

it's a http returned data, and I don't
know if it's an array or string
It's JSON, and you can use it directly in JavaScript.
If you transform it into your array, you will lose the association key / value ; are you sure it's what you want ?

Okay, firstly to get the type of a "thing", use the "typeof" operator (note that the type of an array is an object, not 'array'!):
var a = "string";
var b = 1;
var c = new Array();
alert(typeof(a)); // string
alert(typeof(b)); // number
alert(typeof(c)); // object
To get at the values in the associative array (assuming it is one), you can just loop through it, like so:
var d = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
d["bob"] = "alice";
d["gary"] = "stephen";
for(var key in d) {
alert(d[key]);
}

Related

Array to Object First and Last

I need to take the first and last element in a given array and return an object with the first element as the key and the last as the value.
Here's my code:
function transformFirstAndLast(array) {
array=[];
var object={};
object[key]=value;// make object
var key=array[0];
var value=array[array.length-1];
return object;} // return object
for whatever reason, it's returning undefined inside the object. I swear it was working this morning...
I've always tried:
function transformFirstAndLast(array) {
array=[];
var object = {};
object[array[0]] = array[array.length-1];}
but that's returning undefined without so much as an object being built.
This is straightforward using computed property names:
function transformFirstAndLast(array) {
return {[array[0]]: array[array.length - 1]};
}
Or if you prefer:
const transformFirstAndLast = ([head, ...tail]) => ({[head]: tail.pop()});
You're redeclaring array at the beggining of your function.
Besides, in my opinion, using "array" and "object" as variable names is a bad idea. Just a typo could get you messing up with Array and Object. And that might have side effects.
Here's a functional fiddle for your use case using array.shift() and array.pop() methods.
var myArray=['one','two','three','four'];
function buildObject(arr) {
var myObject={},
key=arr.shift(),
val=arr.pop();
myObject[key]=val;
return myObject;
}
console.log(buildObject(myArray));

How does JSON.stringify make memoize function work?

_ .memoize = function(func) {
var hash = {};
return function() {
var arg = JSON.stringify(arguments);
if (hash[arg] === undefined) {
hash[arg] = func.apply(this, arguments);
}
return hash[arg];
};
};
Hello,
I am trying to implement the memoize underscore function. I have a question regarding to JSON.stringify.
In the if statement where it checks if the arg already exist or not in the hash. Why using JSON.stringify make it possible to check wether the input arg exist or not in the hash. I mean if we pass the arguments array without converting them using JSON.stringify, then we cannot check because we are passing an entire array. However, when using JSON.stringify, it makes it work. So how does JSON.stringify make it possible to check ?
The hash is a JavaScript object, which uses strings as keys. You cannot use an array (or array-like, in the case of arguments) there, so it needs to be converted to a string.
If no custom conversion is done, then the default serialisation would be "[object Arguments]" for any value of arguments. This is not unique and will not work with the intention of memoization.
var hash = {};
var i = 0;
//a naive function that takes anything and puts it in a hash with a unique value
function populateUnique() {
hash[arguments] = "Hello" + i;
i++;
}
populateUnique("a");
populateUnique("b");
populateUnique("c", "d", "e");
console.log(hash); //only shows the last thing, as it it's always overridden.
This implementation chooses to employ JSON.stringify because it is quite straight forward - you could implement a custom serialisation function, but there is already one provided, so this is the simplest way to do it.
Should be noted that JSON.stringify is not bulletproof. It is easy to use and covers a lot of cases, but may blow up, for example, if you have circular references:
var foo = {};
foo.bar = foo;
JSON.stringify(foo);
Since the memoize function does not control what will be passed in as arguments, it's possible that one of them, that is normally perfectly valid, will throw an error.
Another problem is if any of the arguments has its own toJSON method - this will be used for serialization, so you could end up in an interesting situation:
var a = 42;
var b = {
firstname: "Fred",
lastname: "Bloggs",
id: 42,
toJSON: function() { return this.id }
}
console.log(JSON.stringify(b));
console.log(a == JSON.stringify(b));
It's because only strings can be used as keys in javascript objects.
For example:
var key = {a:1};
var map = {};
map[key] = 1;
// {'[object Object]': 1}
This will result in every arguments combination being saved in the same key.
Using JSON.stringify transform the arguments list in an unique string that can in turn be used as an unique object key.
var key = {a:1};
var map = {};
map[JSON.stringify(key)] = 1;
// {'{"a":1}': 1}
This way, every time you call the function with the same arguments, JSON.stringify will return the same unique string and you can use that to check if you already have a cached result for that set of arguments, and if so, returning the cached value.

last index array without loop

Good morning/afternoon
I Want to create an object whitch simulate an array, for new browsers no pb I change the proto of an array with mine but for oldest version of IE i need to know the length of my false array by finding the last index.
I have found a way for IE:
var getLastPos = function(){
for( var i in falseArray){
//do nothing
}
return i
}
but if a faster way exists, it rather like. I try to pass regex to lastindexof
but it seems don't work
thanks.
when you want to find the last index from the array, use
<array>.length
So you do not need the for loop, and your function, use
falseArray.length
If you need the value from the last position use something like this:
falseArray[falseArray.length-1]
//decrement by one, because the index from the array starts by 0
I hope this is helpful.
Thks for you reply,
It was a old question, but I will answer, my goal was to create a false array in order to not polluate prototype.
By false array I mean an object who have the same behavior than a array with .length property and the use of '[]'.
My conclusion is that it is only possible at the class level with new Browser that allow to modify the proto
Ex:
var myClassArray = function(){
var obj = []
obj.__proto__ = myClassArr.prototype
return obj
}
myClassArr.prototype = Array;//inheritance
myClassArr.prototype.last = function(){
return this[this.length-1]
}
or for old browser at object level
var myClassArray = function(){
var obj = []
obj.last= function(){
return this[this.length-1]
}
return obj
}
how to use it:
var myArray = new myClassArray;
console.log(myArray.length) //0
myArray[5]=1;
console.log(myArray.length) //6
console.log(myArray.last()) //1
Conclusion:
Modifiying the proto is a bad idea about perf and old browser.
you can improve the code for old browser by creating function outside the class constructor else browser will duplicate function.
var last = function(){
return this[this.length-1]
}
var myClassArray = function(){
var obj = []
obj.last = last
return obj
}
var a = new myClassArray
var b = myClassArray()//In fact new is facultative
b.last == a.last //same ref no duplication

How to convert v8 Value to Array

I'm writing a c++ extension to v8, and want to pass an Array object into it. I see the incoming argument can be tested by IsArray(), but there isn't a ToArray().
How do you get access to its Length, and request elements by numeric index?
Handle<Value> MyExtension(const Arguments& args)
{
Handle<Value> v = args[0];
if(v->IsArray())
{
// convert to array, find its length, and access its members by index... ?
}
...
}
Must be missing something obvious here. Object can return all its properties, but that's not quite what I was hoping for. Is there a way to get it as an Arrray?
Thanks for reading.
You should use Cast method of a handle to cast it to a different type:
v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(v);
I wasn't able to find a way to convert or cast to Array. Maybe there's a way. But I found by doing object->IsArray(), object->get("length")->Uint32Value(), and object->get(int), I could just walk the array.
v8::Handle<v8::Object> obj;
// ... init obj from arguments or wherever ...
int length = 0;
if(obj->IsArray())
{
length = obj->Get(v8::String::New("length"))->ToObject()->Uint32Value();
}
for(int i = 0; i < length; i++)
{
v8::Local<v8::Value> element = obj->Get(i);
// do something with element
}
i was able to get things working like this, its just a variation of the answer Vyacheslav Egorov gave
Local<Array> arr= Local<Array>::Cast(args[0]);
printf("size %d\n",arr->Length());
Local<Value> item = arr->Get(0);
The below is my succeeded code
v8::Handle<v8::Value> obj(args[0]);
if(obj->IsArray()){
v8::Local<v8::Array> arr= v8::Local<v8::Array>::Cast(args[0]);
v8::String::Utf8Value key(arr->Get(0));
v8::String::Utf8Value value(arr->Get(1));
}

Remove element from Javascript associative array using array value

I am trying to remove an element from a Javascript associtive array using the value to find it, but I am having trouble. I have tried splice and JQuery's grep method and neither have worked for me. This is what I currently have.
var array_path = new Array();
function bulk_upload(){
var temp_array = new Object();
for (var i = 1; i<8; i++){
temp_array[i] = $('#path' + i).val();
if(temp_array[i]!='' && temp_array[i]!=null){
array_path['path' + i] = $('#path' + i).val();
}
}
process_txt();
}
function process_txt(){
//alert(array_path.indexOf(full_path)); //returns nothing
var removed_element = array_path.splice(getKey(array_path), 1);
//array_path = $.grep(array_path, function(val) { return val != full_path; });
alert(removed_element);//return nothing, just blank alert box
}
function getKey(data) {
for (var prop in data)
return prop;
}
The way to do this is to use the delete operator.
delete array_path[getKey(array_path)]
Some Background Information
In JavaScript, almost everything descends from Object.prototype. JavaScript, being an open and dynamic language allows you to create/modify properties of objects by simple assignment. This is very similar to what an associative array -- a structure that contains keyed values.
Under the hood an array is just an object that descends from Array.prototype with numeric keys and a special property called length. The length property just returns one greater than the highest numeric property. In essence, an Array is an object with different semantics.
If you're wanting an associative array then Array is not the object you want to descend from. You would want to descend directly from Object. There are two ways to do that, you could either use the new operator or an empty object literal. The syntax for both is below:
var o = new Object();
var o = {};
The second is preferred since it's a little bit more concise.
I wrote a blog post about this a while back, have a look if you want a little bit more info.
There is no such thing in JavaScript as an "associative array" per se. The data structure which corresponds to this concept is simply a JavaScript Object.
Of course, a JavaScript Array (like essentially everything in JavaScript) is an Object, but one with additional capabilities. So you can use an Array as a key-value map, but it's really not the correct structure for that.
To remove a key from an Object, you just do something like this:
var myObj = {};
var myKey = "blah";
myObj[myKey] = 1234; // Adds or updates value for "blah" to 1234.
delete myObj[myKey]; // Removes key-value pair for "blah".
Have you tried delete hash.someKey; ?
You can give your object a remove method, or use apply or call to use another object's remove method, if defined.
function myObj(members){
for(var p in members) this[p]= members[p];
}
myObj.prototype.remove= function(val){
for(var p in this){
if(this[p]=== val) delete this[p];
}
return this;
}
myObj.prototype.toString= function(){
var A= [];;
for(var p in this){
if(this.hasOwnProperty(p)){
A.push(p+':'+this[p])
}
}
return '{'+A.join(', ')+'}';
}
var O= new myObj({a: 1, b: 10, c: 100});
alert(O)
O.remove(10);
alert(O)
I'm not psychic, so I can only guess that you wanted to accomplish something like this:
var paths = [];
function getPaths() {
for(var i = 1; i < 8; ++i) {
var value = $('#path' + i).val();
if(value) paths.push(value);
}
}
function process() {
var firstPath = paths.shift();
// do stuff
}
getPaths();
if(paths.length) process();

Categories