I have a json as follows.
order =
{
requests: [
{ code: 'T1', id: '123', requestStatus: 'request' },
{ code: 'T2', id: '321', requestStatus: 'request' }
]
}
I want to get an object with key/value pair as follows.
ids['123']='T1'
ids['321']='T2'
I tried with this.
const order =
{
requests: [
{ code: 'T1', id: '123', requestStatus: 'request' },
{ code: 'T2', id: '321', requestStatus: 'request' }
]
};
let id = order['requests'].map((r) => [r.code] = r.id);
console.log(ids['123'] == 'T1');
console.log(ids['321'] == 'T2');
I am getting an error ‘object null is not iterable (cannot read property Symbol(Symbol.iterator))’.
Can someone show me how to do it?
Thanks.
const order = {
requests: [
{code: 'T1', id: '123', requestStatus: 'request'},
{code: 'T2', id: '321', requestStatus: 'request'}
]
};
let ids = {};
order['requests'].forEach(({code, id}) => ids[id] = code);
console.log(ids);
prints
{ '123': 'T1', '321': 'T2' }
Note that I use destructuring assignment to unpack objects in the lambda expression.
You can use the Array.reduce
method:
order = {
requests: [
{code: 'T1', id: '123', requestStatus: 'request'},
{code: 'T2', id: '321', requestStatus: 'request'}
]
}
const ids = order.requests.reduce((acc, req) => {
// Add each property to the accumulator
acc[req.id] = req.code;
return acc;
}, {}); // Start with an empty object
const order = {
requests: [
{ code: 'T1', id: '123', requestStatus: 'request' },
{ code: 'T2', id: '321', requestStatus: 'request' }
]
};
const ids = {};
order.requests.forEach((request) => {
ids[request.id] = request.code;
});
Requests is apparently null by the time you call map
Is
order.requests
assigned in an async function? If so, you’re probably not awaiting it properly.(r: { code: string, id: string })
doesn’t seem to be valid syntax; did you mean{r: { code: string, id: string }}
?Definitely a dupe, just need to find it, but
const ids = Object.fromEntries( order.requests.map(({ code, id }) => [id, code]));
Does this answer your question? How do I convert array of Objects into one Object in JavaScript?