Reputation: 1522
I have an array of objects. I want to pick few values from my array of objects and send it in my request params on for my api that i am calling on componentDidMount. My Array-
const myArray = [
{
id:'73',
name:'ABC',
age: '20',
},
{
id:'74',
name:'XYZ',
age: '21',
},
{
id:'75',
name:'PQR',
age: '22',
},
{
id:'76',
name:'TUV',
age: '23',
}
]
useEffect(
() => {
const newData = myArray.map(list => {
// Logic to add few more keys to existing array
return newData; // new array with few additional properties
});
let data= newData.map(({name, age}) => ({name,age}));
const reqParams = {
userData: {
data: [
{
data,
},
],
},
};
getUserData(reqParams); // API call
[],
);
To get values, I am doing like this-
let result = myArray.map(({name, age}) => name,age)
This will return me an array so, I am not sure if this is the right way to do it. trying to understand how can i pass the values to my request params.
Upvotes: 0
Views: 234
Reputation: 1207
Here is the sample code to achieve the desired output in a single loop 🚀
const myArray = [{
id: '73',
name: 'ABC',
age: '20',
}, {
id: '74',
name: 'XYZ',
age: '21',
}, {
id: '75',
name: 'PQR',
age: '22',
}, {
id: '76',
name: 'TUV',
age: '23',
}]
const newArr = myArray.map((d,index) => {
// return new obj structure with subset of myArray and extra values
const extraData = {
company: 'foo', // adding company & city [read/get it from anywhere]
city:'bar',
sampleIndex: index+1
}
const newObj = {
name: d.name, // not adding id, age
...extraData
}
return newObj
})
console.log("newArr ", newArr)
const reqParams = {
userData: {
data: newArr
},
};
console.log("reqParams ", reqParams)
Upvotes: 1
Reputation: 346
Please try to write the newData calculation as follows if not already:
const newData = myArray.map(list => {
return {
...list,
key: value // additional property
}
});
Upvotes: 0
Reputation: 11305
You can create new object in map callback by wrapping it in ({})
braces
let data= myArray.map(({name, age}) => ({name,age}));
const reqParams = {
userData: {
data
},
};
Upvotes: 0