This is my array :
这是我的阵列:
mapping = [{sl_no : 1, type : "A", parent : ""},{sl_no : 2, type : "B", parent : "A"},{sl_no : 3, type : "D", parent : "B"}]
I want the array in the bellow format :
我希望数组采用以下格式:
mapped_sl_no = [{sl_no : 1},{sl_no : 2},{sl_no : 3}]
4 个解决方案
#1
0
Map is your friend...
地图是你的朋友......
var mapped = mapping.map(function(item) { return item.sl_no; });
#2
0
I suggest to use Array#map()
with a temporary object inside.
我建议使用带有临时对象的Array#map()。
var mapping = [{ sl_no: 1, type: "A", parent: "" }, { sl_no: 2, type: "B", parent: "A" }, { sl_no: 3, type: "D", parent: "B" }],
mapped_sl_no = getMapped(mapping, 'sl_no');
function getMapped(array, k) {
return array.map(function (a) {
var o = {};
o[k] = a[k];
return o;
});
}
document.write('<pre>' + JSON.stringify(mapped_sl_no, 0, 4) + '</pre>');
#3
0
Solution with map
function:
地图功能解决方案:
var mapping = [{sl_no : 1, type : "A", parent : ""},{sl_no : 2, type : "B", parent : "A"},{sl_no : 3, type : "D", parent : "B"}];
var arr = mapping.map(function(obj){
return {'sl_no': obj.sl_no};
})
console.log(arr); // the output is: [{sl_no : 1},{sl_no : 2},{sl_no : 3}]
#4
0
var mapped_sl_no = [];
mapping.forEach(function(mapVal){
mapped_sl_no.push({sl_no:mapVal.sl_no});
});
This should do it for you.
这应该为你做。
Else you can use libraries like underscore(http://underscorejs.org/) or lowdash(https://lodash.com/)
否则你可以使用像下划线(http://underscorejs.org/)或lowdash(https://lodash.com/)这样的库
#1
0
Map is your friend...
地图是你的朋友......
var mapped = mapping.map(function(item) { return item.sl_no; });
#2
0
I suggest to use Array#map()
with a temporary object inside.
我建议使用带有临时对象的Array#map()。
var mapping = [{ sl_no: 1, type: "A", parent: "" }, { sl_no: 2, type: "B", parent: "A" }, { sl_no: 3, type: "D", parent: "B" }],
mapped_sl_no = getMapped(mapping, 'sl_no');
function getMapped(array, k) {
return array.map(function (a) {
var o = {};
o[k] = a[k];
return o;
});
}
document.write('<pre>' + JSON.stringify(mapped_sl_no, 0, 4) + '</pre>');
#3
0
Solution with map
function:
地图功能解决方案:
var mapping = [{sl_no : 1, type : "A", parent : ""},{sl_no : 2, type : "B", parent : "A"},{sl_no : 3, type : "D", parent : "B"}];
var arr = mapping.map(function(obj){
return {'sl_no': obj.sl_no};
})
console.log(arr); // the output is: [{sl_no : 1},{sl_no : 2},{sl_no : 3}]
#4
0
var mapped_sl_no = [];
mapping.forEach(function(mapVal){
mapped_sl_no.push({sl_no:mapVal.sl_no});
});
This should do it for you.
这应该为你做。
Else you can use libraries like underscore(http://underscorejs.org/) or lowdash(https://lodash.com/)
否则你可以使用像下划线(http://underscorejs.org/)或lowdash(https://lodash.com/)这样的库