0

var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = {}

for(var i=0; i<a.length; i++){
                c[a[i]] = b[i]
            }

document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

Above loop produced

{
    "Child": 2,
    "Adult": 6
}

but how to produce the resutl like this

[{"child":2},{"Adult":6}]

which later on is easy for me to loop through.

5
  • @Alicia if OP asked for [{"child":2},{"Adult":6}] it's not a valid edit to improve the expected result format to something like {"type":"child", "pax":2} if not explicitly requested by OP. Commented Oct 23, 2015 at 2:44
  • The OP asked for that output saying that it would be easy to loop through, which is clearly false. Looping through the new structure will require more code than the original, and require fun stuff like use of Object.keys to extract the names "Child" and "Adult", called on an object with a single property. Commented Oct 23, 2015 at 3:12
  • @James: but imagine if a were something like ["Child", "Child", "Adult"], a simple flat object would only be able to handle a unique array, and for-in can handle the nested iteration. Commented Oct 23, 2015 at 3:44
  • Oh, you have asked this recently, and I have provided the correct code in your previous question :) stackoverflow.com/questions/33278209/… Commented Oct 23, 2015 at 3:46
  • @dandavis I agree, what's needed is an array of arrays, or an array of objects with sensible property names. Commented Oct 23, 2015 at 3:49

7 Answers 7

2
var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = []

for(var i=0; i<a.length; i++){
                var o = {}
                o[a[i]] = b[i];
                c.push(o)
            }

if you use a functional library like Ramda, then you can do :-

R.zipWith(R.createMapEntry,a,b);
Sign up to request clarification or add additional context in comments.

1 Comment

awsome. this is slick
1

Simple and procedural.

Obviously c should be an array, judging by the output you want. So in the loop you just have to create an object with the right key and value and add that to the array c.

var a = ['Child', 'Adult'];
var b = [2,6];
var c = [];

for (var i = 0 ; i < a.length ; i++) {
  var key = a[i];
  var val = b[i];
  var obj = {};
  obj[key] = val;
  c[i] = obj;
}

document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

More functional with map.

As mentioned in other answers: There are more functional programming oriented ways of doing this. The above code is as simple as possible in order to help you learn.

You could also do something like:

var a = ['Child', 'Adult'];
var b = [2,6];

c = a.map(function(key,i) {
  var obj = {};
  obj[key] = b[i];
  return obj;
});

document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

Considering you have to access array b with an index anyways I wouldn't say this way is any better.

Even more functional with zip and map.

A more functional way would be to combine a and b using a zip function and then map that to a new array.

var a = ['Child', 'Adult'];
var b = [2,6];

function zip(arrays) {
  return arrays[0].map(function(_,i){
    return arrays.map(function(array){return array[i]})
  });
}

var c = zip([a,b]).map(function(obj) {
  var result = {};
  result[obj[0]] = obj[1];
  return result;
});

document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

Comments

0

You are setting var c as an object, but expecting it to be an array. Try:

var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = []

for(var i=0; i<a.length; i++){

    var temp = {};
    temp[a[i]] = b[i];

    c.push( temp );
}

1 Comment

Sorry. Used to the PHP syntax. Edited and tested.
0

var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = [];

for(var i=0; i<a.length; i++){
                c[i] = {};
                c[i][a[i]] = b[i];
            }

document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

Comments

0

Try using Array.prototype.map() , moving c into callback to create object for each item in a

var a = ["Child", "Adult"];
var b = [2, 6];

var arr = a.map(function(val,key) {
  var c = {};
  c[val] = b[key];
  return c
});



document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>

Comments

0

Something like this should do.

var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = [];

for(var i=0; i<a.length; i++){
  var obj = {}; // create a temp object
  obj[a[i]] = b[i]; // fill the values 
  c.push(obj); // push it to c
}

Comments

0

in firefox (and ES6 or chrome with experimental JS flag in about:flags set), you can do this neat little trick:

var a = [ 'Child' , 'Adult'];
var b = [2,6];

a.map(  (a,i)=> a={[a]: b[i]}  ); // == [{"Child":2},{"Adult":6}]

(sadly the a= part is needed to make it not look like a function body, but it's harmless anyway...

if you don't mind destroying the array, this is slightly cleaner reading:

a.map( a => a={[a]: b.shift()} );

I think it's neat than plain vanilla can do this task with fewer chars of code than something like Ramda...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.