guialmpin
guialmpin

Reputation: 25

JavaScript: How can we create as many objects as necessary based on one array/vector lenght?

How can we create as many objects as necessary based on one array/vector lenght in JavaScript? Can we do it in a simple way as an amateur (me) would expect?

Suppose we have the following: (snippet not working, yet)

It's possible to populate an array (x) with objects this way? Thanks!

<!DOCTYPE html>
<html>
<body>
<h1>TEST:</h1>
<input onclick="running()" type="submit" value="RUN TEST">
<script>
    function running(){

        array1 = ["A","B","C"]; /*array1 and array2 => same lenght*/
        array2 = [10,20,30];

        function Obj(letters, numbers) {this.letters = letters; this.numbers = numbers;}

        function CreateObj(array1,array2){
                    var x = [];
                    for (var i=0;i<=array1.length;i++){
                        var created = new Obj();
                        created.letters= array1[i];
                        created.numbers= array2[i];
                        x.push(created);
                    }
                    return  alert(x);
        }
    CreateObj(array1,array2)
    }
</script>
</body>
</html>

EDIT: I've solved for what I need in a simpler way (at least for me, it's easier to understand what is going on):

    function Obj(letters, numbers) {this.letters = letters; this.numbers = numbers;}
    array1 = ["A","B","C"]; /*array1 and array2 => same lenght*/
    array2 = [10,20,30];

    function CreateObj(array1,array2) {
            var x = [];
            for (var i=0;i<=array1.length-1;i++){
                var newArray = new Obj(array1[i],array2[i]);
                x.push(newArray);
            }
            return console.log(x); /*returns an Array with array1.length objects...*/
    }
CreateObj(array1,array2);

Upvotes: 0

Views: 79

Answers (1)

Mark
Mark

Reputation: 92440

If I understand what you are trying to do, a simple map is probably the cleanest:

const array1 = ["A","B","C"]; /*array1 and array2 => same lenght*/
const array2 = [10,20,30];

function Obj(letters, numbers) {this.letters = letters; this.numbers = numbers;}
let mapped = array1.map((item, i) => new Obj(item, array2[i]))

console.log(mapped)

Upvotes: 1

Related Questions