admin管理员组文章数量:1295693
I have a array like this with 1000+ rows:
Now I need to create a new array (named as $scope.roleUsers) and copy only deptCode and roleName in to the new array
I used slice, but it can be used to select the value by index but here I need to push the specific field by name into the new array. excepted like this :
$scope.roleUsers = [{deptCode: "8", roleName : "Deo Role"}, {deptCode: "4", roleName : "BMRole"}]
Please assist here, thanks in advance.
I have a array like this with 1000+ rows:
Now I need to create a new array (named as $scope.roleUsers) and copy only deptCode and roleName in to the new array
I used slice, but it can be used to select the value by index but here I need to push the specific field by name into the new array. excepted like this :
$scope.roleUsers = [{deptCode: "8", roleName : "Deo Role"}, {deptCode: "4", roleName : "BMRole"}]
Please assist here, thanks in advance.
Share asked Oct 31, 2019 at 6:27 Mar1009Mar1009 8112 gold badges13 silver badges29 bronze badges4 Answers
Reset to default 6.slice
only creates a copy of the array (possibly from one index to another), it doesn't change any of the elements - you want .map
instead:
const result = $scope.deoUsers.map(({ deptCode, roleName }) => ({ deptCode, roleName }));
You can use array.map
function & in the call back function return an object which have only the required keys
let arr = [{
deptCode: "8",
roleName: "Deo Role",
id: 1
}, {
id: 2,
deptCode: "4",
roleName: "BMRole"
}]
let newArr = arr.map((item) => {
return {
deptCode: item.deptCode,
roleName: item.roleName
}
});
console.log(newArr)
You can use map
to get specific fields from array data like below -
let deoUsers = [{deptCode: "8", roleName : "Deo Role", userName: '123'}, {deptCode: "4", roleName : "BMRole", userName: '456'}]
, roleUsers = deoUsers.map(({deptCode, roleName}) => ({deptCode, roleName}))
console.log(roleUsers)
You can use Array.map method for copying specific elements.
var demoObject = [{
fname: 'John',
lname: 'Doe' ,
rollNo: 123
}, {
fname: 'John',
lname: 'Doe' ,
rollNo: 345
}];
var requiredRes = {
Objects: demoObject.map(function(v) {
return {
rollNo: v.rollNo
};
})
}
console.log(requiredRes);
Reference: https://stackoverflow./a/38050206/10971575
本文标签: javascriptCreate a copy of an array but with only specific fieldsStack Overflow
版权声明:本文标题:javascript - Create a copy of an array but with only specific fields - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741622901a2388913.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论