我有一个对象数组
var arr1 = [{
"amount": 700,
"hits": 4,
"day": 1
},
{
"amount": 100,
"hits": 7,
"day": 4
},
{
"amount": 500,
"hits": 3,
"day": 8
}
];
我需要的是创建一个新的对象数组,使用key" param"在每个对象中,以及" param"的值应该等于"金额" arr1对象中的字段。
预期产出:
var newArr = [{
"param": 700
},
{
"param": 100
},
{
"param": 500
}
];
答案 0 :(得分:3)
您可以使用Array.prototype.map():
var arr1 = [{"amaunt": 700,"hits": 4,"day": 1}, {"amaunt": 100,"hits": 7,"day": 4}, {"amaunt": 500,"hits": 3,"day": 8}],
newArr = arr1.map(function(elem) {
return {param: elem.amaunt};
});
console.log(newArr);
答案 1 :(得分:2)
var newArr = []
arr1.forEach(obj => {
newArr.push({param: obj.amount});
});
答案 2 :(得分:2)
尝试使用map:
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var arr2 = arr1.map(function(obj) {
return {param: obj.amaunt};
});
console.log(arr2);
答案 3 :(得分:1)
你可以试试这个
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var newArr=[];
arr1.forEach(function(item){
newArr.push({"param":item.amaunt});
});
console.log(newArr);
答案 4 :(得分:0)
答案 5 :(得分:0)
另一种方法可以做到这一点
var newArr=[];
arr1.map(function(obj) {
newArr.push("param:"+obj.amaunt);
});