I am looking for a way to i convert this.
const data = [{
id: 1,
fullnames: 'JosephSam',
weight: 1231,
currentdate: '2021-09-22'
}]
into this
const data = {
id: 1,
fullnames: 'JosephSam',
weight: 1231,
currentdate: '2021-09-22'
}
CodePudding user response:
If you have multiple values inside your array, then you can have a separate object to insert each array value into it by having id as the object key.
Take a look at the following example.
const data = [
{
id: 1,
fullnames: "JosephSam",
weight: 1231,
currentdate: "2021-09-22",
},
{
id: 2,
fullnames: "Jane",
weight: 1431,
currentdate: "2021-09-22",
},
];
const mappedData = {};
data.forEach((element) => (mappedData[element.id] = element));
console.log("Mapped Data: ", mappedData);
Console log
Mapped Data: {
'1': {
id: 1,
fullnames: 'JosephSam',
weight: 1231,
currentdate: '2021-09-22'
},
'2': { id: 2, fullnames: 'Jane', weight: 1431, currentdate: '2021-09-22' }
}
Then you can refer each element by id as follows. (x
is the id you need to get)
mappedData[x]
CodePudding user response:
const arr = [{
id: 1,
fullnames: 'JosephSam',
weight: 1231,
currentdate: '2021-09-22'
}];
const data = arr[0];
console.log(data.fullnames); // 'JosephSam'
This would be what you need. I do get the feeling this is isn't what you're looking for. If so, please give us a more complex example to see what it is you're dealing with.
CodePudding user response:
I'm not sure what are you trying to do. But If you have a single indexed array you should to this:
var data = [{
id: 1,
fullnames: 'JosephSam',
weight: 1231,
currentdate: '2021-09-22'
}]
data = data[0];