json 如何基于key迭代对象并移除其余项

vc9ivgsu  于 2022-11-19  发布在  其他
关注(0)|答案(3)|浏览(143)

我有这个json文件,我试图过滤数据,只保留用户:“11111”,但它不工作。

var data= [
  {
    id: {
      server: 'xxxxx',
      user: '123456',
      _serialized: '64566'
    },
    name: 'Doe',
    isCalled: false,
    isReceived: false,
    unreadCount: 1,
  },
  {
    
    id: {
      server: 'xxxxx',
      user: '123456',
      _serialized: '64566'
    },
    name: 'Doe',
    isCalled: false,
    isReceived: false,
    unreadCount: 1,

  },
  {
    
    id: {
      server: 'xxxxx',
      user: '123456',
      _serialized: '64566'
    },
    name: 'Doe',
    isCalled: false,
    isReceived: false,
    unreadCount: 1,

  }
]

我试过了

const seun = sex.map(({ id, ...rest }) => rest);

但没有奏效

预期结果:

var data= [
  {
    
      user: '123456'
     
    },
   
  {
    
    
      user: '123456',
    
    },
   
  {
   
      user: '123456',
     
    },
   

  }
]
xxhby3vn

xxhby3vn1#

array.map( x => f(x) )这将遍历数组的元素,并返回一个新数组,其元素为f(x)

const data = [
  {
    "id": { "server": "xxxxx", "user": "123456", "_serialized": "64566" },
    "name": "Doe",
    "isCalled": false,
    "isReceived": false,
    "unreadCount": 1
  },
  {
    "id": {
      "server": "xxxxx",
      "user": "123456",
      "_serialized": "64566"
    },
    "name": "Doe",
    "isCalled": false,
    "isReceived": false,
    "unreadCount": 1
  },
  {
    "id": {
      "server": "xxxxx",
      "user": "123456",
      "_serialized": "64566"
    },
    "name": "Doe",
    "isCalled": false,
    "isReceived": false,
    "unreadCount": 1
  }
]

const newData = data.map(d => ({ "user": d.id.user }));

console.log(newData)
bxgwgixi

bxgwgixi2#

您可以将Array.prototype.map()destructuring assignment结合使用

const data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}]

const result = data.map(({ id: { user } }) => ({ user }))

console.log(result)
t1rydlwq

t1rydlwq3#

Array#map(参见@YosvelQuintero的答案)是最好的方法。在这里我将说明您也可以使用Array#reduce方法:

const 
    data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}],

    output = data.reduce(
        (acc, { id: { user } }) => [...acc,{ user }],[]
    );

console.log( output );

相关问题