如何转换我的数组:
["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"]
到对象数组:
["title": "Collaboration", "title":"Personal", "title":"Services", "title":"Financial", "title":"Enginerring", "title":"Infrastructure", "title":"Application", "title":"null"]
我做了类似的事情:
var mainmenu = [];
for(var i=0; menus.length > i;i++){
mainmenu[i] = "{title:"+menus[i]+"}";
}
但我得到了:
["{title:Collaboration}", "{title:Personal}", "{title:Services}", "{title:Financial}", "{title:Enginerring}", "{title:Infrastructure}", "{title:Application}"]
那么如果没有双引号怎么可能呢?
答案 0 :(得分:4)
尝试使用.map
var data = ["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"];
var result = data.map(function (title) {
return { title: title };
})
console.log(result);
在您使用String
代替Object
的代码问题中,请移除"
mainmenu[i] = { title: menus[i] };
^^^ ^^ ^^ ^^^
答案 1 :(得分:1)
那是因为你正在创建字符串而不是实际的对象。创建这样的对象:
mainmenu[i] = {
title: menus[i]
};
答案 2 :(得分:0)
es6
public class DebuggerPagerAdapter extends FragmentPagerAdapter {
public DebuggerPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return MemoryFragment.getInstance();
case 1:
return NetworkFragment.getInstance();
case 2:
return CpuFragment.getInstance();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
ES5
var data = ["Collaboration", "Personal", "Services", "Financial","Enginerring", "Infrastructure", "Application", "null"];
data.map(function(title) {
return {
title: title
}
})
答案 3 :(得分:0)
这是一个可以使用Array.from()
的好例子:
Array.from()方法从中创建一个新的Array实例 类似数组或可迭代的对象。
在ES6中,类语法允许内置和子类的子类化 用户定义的类;因此,类侧静态方法如
Array.from
是“继承”由Array的子类创建并创建新的 子类的实例,而不是Array。
var data = ["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"];
console.log(Array.from(data, x => ({title : x})));