如何通过从另一个对象中选择特定属性来克隆新的对象数组?

时间:2019-04-30 10:39:23

标签: javascript html arrays node.js json

所以

我收到的数据包含以下信息:

{  
   "data":[  
      {  
         "vote_count":22222,
         "id":299537,
         "ready":false,
      },
      {  
         "vote_count":2850,
         "id":299534,
         "ready":true,
      },
     ]
}

现在,我需要制作一个包含相同结构但具有一些属性的新对象,即:

{
  "data": [
   {
      "ready":false,
   },
   {
      "ready":true,
   }
 ]
}

我需要可扩展的解决方案,假设有一组具有50个属性的数据。另外,我确实找到了对象的解决方案,但从来没有对象数组的解决方案。

谢谢大家,我已经头昏了三个小时。

3 个答案:

答案 0 :(得分:3)

您可以使用destrcuturingshorthand property names创建新的对象,如下所示:

const input={"data":[{"vote_count":22222,"id":299537,"ready":false,},{"vote_count":2850,"id":299534,"ready":true,},]}

const data = input.data.map(({ ready }) => ({ ready }))

console.log({ data })

如果要获取一堆属性,则可以创建所需的属性数组。然后使用Object.assign()reduce创建每个对象的子集,如下所示:

const input={"data":[{"vote_count":22222,"id":299537,"ready":false,},{"vote_count":2850,"id":299534,"ready":true,},]}

const properties = ["vote_count", "ready"]

const data = input.data.map(a => 
  Object.assign({}, ...properties.map(p => ({ [p]: a[p] })))
)

/* You could also use reduce like this:
  input.data.map(a => properties.reduce((r, p) => ({ ...r, [p]: a[p] }), {}))
*/

console.log({ data })

答案 1 :(得分:1)

映射所需的属性

var obj1 = {  
   "data":[  
      {  
         "vote_count":22222,
         "id":299537,
         "ready":false,
      },
      {  
         "vote_count":2850,
         "id":299534,
         "ready":true,
      },
     ]
}
var obj2 = {}
obj2.date = obj1.data.map(data => ({ ready: data.ready}));
console.log(obj2)

答案 2 :(得分:1)

您可以使用Array#map方法和Array#reduce方法

const input = {
  "data": [{
      "vote_count": 22222,
      "id": 299537,
      "ready": false,
    },
    {
      "vote_count": 2850,
      "id": 299534,
      "ready": true,
    },
  ]
}
const extract = ['ready']

const data = input.data.map(o => extract.reduce((obj, k) => (obj[k] = o[k], obj), {}))

console.log({ data })