如何创建一个javascript函数,输出一个带有object's属性列表的对象列表

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

本文关键字:一个 列表 属性 object 对象 创建 何创建 javascript 函数 输出      更新时间:2023-09-26

我有一段javascript,看起来像下面的

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

由于property1property2对于所有对象都是空的,所以我想将其自动化,这样我只需要跟踪名称。比如:

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

表明magicFunction可以返回上面提到的set。我是非常新的javascript,如果你认为这是太基本的stackoverflow,请给我几个关键字,让我知道我应该搜索什么。谢谢!

您可以使用 map

nameList得到set

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>

听起来好像你需要使用一个构造函数,然后从中'构造'或返回对象并存储在你的集合中:

// 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

一个解决方案:

/* 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) );

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;
}