1

I think my problem isn't that hard but I'm kinda new in javascript... so my question is how to make something like the following (the following doesn't work):

var t1 = {
    0 : "lel",
};
var t2 = {
    t1[0] : 1,
};
Crispy
  • 65
  • 7
  • * the t2 array should look like t2["lel"] = 1 – Crispy Aug 24 '17 at 17:52
  • 1
    use `[t1[0]]: 1` but this has nothing to do with arrays. See [computed property names](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – ASDFGerte Aug 24 '17 at 17:53
  • Take a look at [associative arrays](http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html) – Josh Evans Aug 24 '17 at 17:55
  • i like this solution even more, great that it's possible to construct an array like that, thanks! – Crispy Aug 24 '17 at 17:59

3 Answers3

2

You can simply use t2[t1[0]] = 1 like this:

var t2 = {};
t2[t1[0]] = 1;

Demo below:

var t1 = {
  0: "lel",
};
var t2 = {};
t2[t1[0]] = 1;

console.log(t2);
kukkuz
  • 41,512
  • 6
  • 59
  • 95
1

With ES, you could use computed property names for it.

var t1 = { 0 : "lel" },
    t2 = { [t1[0]]: 1 };

console.log(t2);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

An array literal in javascript looks like this:

var a = [val1, val2, val3];

If you want to put a value from one array into another array you can do this:

var a1 = [val1, val2, val3];
var a2 = [a1[0], a1[1], a1[2]];

If you want to use the value as a key for an object you have to do:

var a = [someValue];
var b = {[a[0]]: someOtherValue};

Or if you need to support older browsers:

var b = {};
b[a[0]] = someotherValue;

Keep in mind that there are better ways to take data from one array and put it into another array or into an object look at map or reduce and similar functions. Or you could look at using a library like lodash, which is great for array and object manipulation.

Joseph Ditton
  • 998
  • 8
  • 7