return 0
return 0

Reputation: 4366

How to create a javascript function that output a list of object with a list of the object's property?

I have a piece of javascript that looks like the following

var set = [{
  name: 'a',
  property1: '',
  property2: '',
},
{
  name: 'b',
  property1: '',
  property2: '',
},
{
  name: 'c',
  property1: '',
  property2: '',
}];

Since property1 and property2 are both empty for all objects, I want to automate this such that I only need to keep track of the name. Something like:

namelist = ['a', 'b', 'c'];
magicFunction(namelist);

that magicFunction can return that set I mentioned above. I am very new to javascript, if you think this is too rudimentary for stackoverflow, please give me a few keywords so I know what I should be searching for. Thanks!

Upvotes: 2

Views: 647

Answers (4)

ricky
ricky

Reputation: 1674

function magicFunction(nameList){
var set = [];


for(var i = 0; i<nameList.length;i++){
  var temp = new Object();
  temp.property1='';
  temp.property2='';
  temp.name=nameList[i];
  set.push(temp);  
}
  return set;
}

Upvotes: 0

Anonymous0day
Anonymous0day

Reputation: 3042

One solution :

/* instead of console.log */
function log(val){
    document.write('<pre>' + JSON.stringify( val , null , ' ') + '</pre>');
};


function magicFunction( listOfNames ) {
  return listOfNames.map(function( currentValue ){
    return {
      name       : currentValue ,
      property1  : '',
      property2  : '',
    };
  })
};

var namelist = ['a', 'b', 'c' , 'd' , 'e' , 'f'];
log( magicFunction(namelist) );

Upvotes: 0

sheriffderek
sheriffderek

Reputation: 9043

Sounds to me like you need to use a constructor function and then 'construct' or return objects from that and store in your set:

// quick array
var someArray = ['a', 'b', 'c'];
// define array for output
var set = [];
// constructor to create the objects
function something(name, param1, param2) {
    this.name = name;
    this.property1 = param1;
    this.property2 = param2;
}
// run through the quick array and build the objects with the constructor - push into 'set'
var magicFunction = function(arrayName) {
  for (var i = 0; i < arrayName.length; i++) {
    set.push( new something( someArray[i] ) );
  }
}

magicFunction(someArray);

console.log(set);

jsFiddle

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can use map

To get set from nameList

var namelist = ['a', 'b', 'c'];
var set = namelist.map(function(e) { return { name: e, property1: 0, property2: 0 }});

function magicFunction(arr) {
  return arr.map(function(e) {
    return {
      name: e,
      property1: 0,
      property2: 0
    }
  });
}

var namelist = ['a', 'b', 'c'];
set = magicFunction(namelist);

console.log(set);
document.getElementById('output').innerHTML = JSON.stringify(set, 0, 2);
<pre id="output"></pre>

Upvotes: 5

Related Questions