JavaScript: Functional mapping?

Is there a shorter way to write this?

var me = {}; for (var i in you) { me[i] = you[i]; } 

(where you is a randomly-extended JavaScript array)

In other words, given the input:

 var you = [ "what", "r", "u" ]; 

The output signal me becomes:

 me = { 0: "what", 1: "r", 2: "u" }; 

Like, a single line that uses some kind of functional method?

+4
source share
5 answers

Why would you want to do that? Arrays in JavaScript are objects , with the exception of some additional properties, such as slice , splice , push and length .

Internally, arrays and objects are stored in exactly the same way: for example. array[0] is the same as array["0"] , or object["0"] (unlike other languages โ€‹โ€‹where adjacent array indices are actually in adjacent memory. "Array indices" are simply converted to strings in JavaScript).

So, if you just want to copy the data, this will be enough:

 me = you.slice(); // me is a copy of you, but is still an array 

Or, if you really need some kind of mapping function, underscore.js provides a whole collection of functional programming tools for your reading.

+3
source

There is no built-in function that does what you ask for, however some of the widely used javascript libraries like jQuery provide such a function. In the case of jQuery: jQuery.extend()

Using:

 var me = {}; jQuery.extend(me,someObject); //or, equivalently - var me2 = jQuery.extend({},someObject); 
+1
source

jQuery has an extend() function ( here ). Your code will look like this:

 var me = {}; var you = ["what", "r", "u"]; $.extend(me, you); 

This will allow you to do things like:

 alert("Second element: " + me[1]); 

A bit strange, but I think this is what you are looking for.

0
source

I saw what you were trying to achieve with string formatting. Instead of answering your initial question about how to proceed with a brief implementation of one part of it, I offer a brief (and more flexible) implementation for everything:

 String.prototype.format = function () { var args = arguments; return this.replace(/\{(?:(\d+)|(\w+))\}/g, function (s, idx, prop) { return prop && args[0] ? args[0][prop] : args[idx]; }); }; 

When you have the number n inside the token "{n}" , it uses the nth argument to replace it. Otherwise, for non-numeric keys, it selects the corresponding property of the first argument.

For instance:

 "I have {1} {name}s in my basket.".replace({ type: "fruit", name: "eggplant" }, 4); 

Return:

 "I have 4 eggplants in my basket." 
0
source

The underscore.js library also has a basic extension function.

var me = _({}).extend(you)

or

 var me = {} _(me).extend(you) 

or

 var me = {} _.extend(me, you) 
0
source

Source: https://habr.com/ru/post/1337901/


All Articles