I have this json file and i have tried to filter the data keep only the user:'11111', but its not working.
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,
}
]
i tried
const seun = sex.map(({ id, ...rest }) => rest);
but did not work
desired result:
var data= [
{
user: '123456'
},
{
user: '123456',
},
{
user: '123456',
},
}
]
CodePudding user response:
array.map( x => f(x) )
this will iterate over the elements of array, and return a new array whos elements are the 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)
CodePudding user response:
You can use Array.prototype.map() combined with 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)
CodePudding user response:
Array#map
(see @YosvelQuintero's answer) is the best method to use. Here I show that you may also use the Array#reduce
method:
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 );