如何创建一个javascript函数,输出一个对象列表与对象的属性列表?

时间:2015-10-15 06:15:34

标签: javascript arrays

我有一段类似于以下内容的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来说太基础了,请给我一些关键字,以便我知道我应该搜索什么。谢谢!

4 个答案:

答案 0 :(得分:5)

您可以使用map

import javax.swing.JOptionPane; import java.lang.*; public class FormatPhoneNumber { public static void main(String[] args) { final int numLength=10; String phoneNum = null; String nineS="999"; phoneNum=JOptionPane.showInputDialog(null, "Enter your telephone number"); while (phoneNum.length()!=numLength) {phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number."); } StringBuffer str1 = new StringBuffer (phoneNum); str1.insert(0, '('); str1.insert(4, ')'); str1.insert(8, '-'); JOptionPane.showMessageDialog(null, "Your telephone number is " +str1.toString()); while (phoneNum.contains(nineS))// THIS IS THE ISSUE { } } }

获取set
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);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

一个解决方案:

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