0

Hi I'm trying to make an array of objects from several arrays.This is probably a very basic question, but I didn't find a proper way of doing it from searching online. :(

The original data I've got is

valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];

What I want to achieve is an array like :

data = [object1, object2,.....]

Each object is made of :

object1 = {valueYes:15, valueNo:23,valueNotSure:1}
object2 = {valueYes:30, valueNo:75,valueNotSure:-1}
.......

my current code is a bit messy, which only return me an empty value of each key:

valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];

var object1 = Object.create({}, { 
    myChoice: { value: function(myChoice) {for  (var i = 0; i < len; i++){return this.myChoice[i] = myChoice[i];} } } 

});

3 Answers 3

6

Assuming all your arrays have the same size:

valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];

var data = [];

for(var i = 0; i < valueYes.length; i++){
    data.push({
        valueYes: valueYes[i],
        valueNo: valueNo[i],
        valueNotSure: valueNotSure[i]
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

ah, this is the thing I'm looking for, very clear! thank you!
3

You could use something like below;

var objs = valueYes.map(function (v, i) {
    return {
        valueYes: v,
        valueNo: valueNo[i],
        valueNotSure: valueNotSure[i]
    };
});

... this uses the map() Array method, and assumes that all the arrays are the same length...

2 Comments

Yeah, I considered map, but thought the loop might be clearer, given the OP's level...
Nice & elegant solution with .map()
0

This?

var valueYes = [15,30,22,18,2,6,38,18];
var valueNo = [23,75,45,12,45,9,17,23];
var valueNotSure = [1,-1,1,1,-1,-1,-1,1];

var data = [];
valueYes.forEach(function(item, index) {
    data.push({ valueYes: valueYes[index], valueNo: valueNo[index], valueNotSure: valueNotSure[index] });
});

console.log(data);

http://jsfiddle.net/chrisbenseler/9t1y1zhk/

2 Comments

Why would you use forEach and push when map does exactly the same thing? And why would you use valueYes[index] when you already have it in item?
You need the index because you have to get the [index] of the other 2 arrays. The "item" references only values from the valueYes array. And I didn't thought about using .map(). I have also commented on Matt's post that use .map() is very elegant ;-)

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.