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 badges
Add a ment  | 

4 Answers 4

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