如何创建一个javascript函数,输出一个带有object's属性列表的对象列表
How to create a javascript function that output a list of object with a list of the object's property?
我有一段javascript,看起来像下面的
var set = [{
name: 'a',
property1: '',
property2: '',
},
{
name: 'b',
property1: '',
property2: '',
},
{
name: 'c',
property1: '',
property2: '',
}];
由于property1
和property2
对于所有对象都是空的,所以我想将其自动化,这样我只需要跟踪名称。比如:
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;
}
相关文章:
- 从javascript创建一个列表
- 使用jquery从列表项中移除类,并将一个类添加到另一个列表项中
- 为数组Jquery/Javascript创建一个列表函数
- JavaScript,如何从一个列表中获取选定的值,同时在另一个列表中进行更改
- 如何在选择另一个列表框值时清除列表框值
- Angular2从数组创建一个列表
- 为什么此脚本仅应用于此列表中的一个列表项
- Jquery幻灯片中的列表,连接第一个和最后一个列表元素以创建旋转木马
- 如何从有序列表中选择一个列表元素
- 雄辩的Javascript:练习:一个列表
- 将单元格的高度从一个表列表指定到另一个列表
- AngularJS图像在点击时应该显示一个列表
- 从 AJAX 在 JavaScript 中创建一个列表
- 如何使用列表框的一个值来设置另一个列表框的值
- 在两个或多个 UL 列表之间切换,如果单击一个列表,则其他列表会自动以初始状态返回,就像从未单击过一样
- Jquery UI 可排序和可删除 - 无法将项目从一个列表克隆到另一个列表
- 使用 JQuery 将元素从一个列表移动到另一个列表
- 我有一个列表显示 1、2、3 个数字,我可以将它们转换为乌尔都语吗?
- 一个列表的Mailchimp多个订阅表单
- jQuery - 一个列表中的每个列表在另一个列表之前