#restructing data

1 messages · Page 1 of 1 (latest)

stray oracle
#

Hey guys, If I have some data like

[{name: "Andrew", age: 20}, {name: "Mike", age: 20}, {name: "Michells", age: 25}, {name: "Tom", age: 16}, {name: "Mace", age: 25}]```

how do I possibly restructure it to something like 
```js
[{age: 20, name: ["Andrew", "Mike"]}, {age: 16, name: ["Tom"]},{age: 25, name: ["Mace", "Michells"]}]
molten epoch
#

You can do smth like this:

data.reduce((result, current) => {
const { age, name } = current;
result[age] ??= { age, names: [] };
result[age].names.push(name);
return result;
}, {});

If you do need the array and not an object you can use Object.Values on the returned value of the reduce. Wrote this on mobile so there might be something whacky going on.. You‘ll figure it out ChibiWinkk

cosmic owl
#

Nope, works fine sunglassesvery3dcool

molten epoch
#

PogMe

cosmic owl
#

And yea, Object.values gives the original desired result. Though at that point you may as well just loop through the object

molten epoch
#

Yeah not sure what the output will be used for so just to be safe shrug

stray oracle
#

result[age] ??= { age, names: [] }; what does this imply @cosmic owl @molten epoch

molten epoch
stray oracle
#

Oh gotcha

stray oracle
# cosmic owl And yea, `Object.values` gives the original desired result. Though at that point...

OKay so I am trying to implement this logic to my code, the idea is similar but the data is different

const populateJobs = async () => {
  const data = await fetch("https://getlumen.com/_/lever");
  const allJobs = await data.json();
  const filteredJobs = allJobs.map((job) => {
    return {
      applyUrl: job.applyUrl,
      team: job.categories.team,
      text: job.text,
    };
  });
console.log(filteredJobs)
const final = Object.keys(filteredJobs.reduce((result, current) => {
const { team, applyUrl, text } = current;
result[team] ??= { team, info: [applyUrl, text] };
result[team].info.push(applyUrl, text);
return result;
}, {}));
console.log(final)
};
populateJobs();

You can run this in chrome console if you'd like

I get this result when I do so ( ss attached )

Although expected result is that all the items are categorised under team
just like age

#

I don't understand what I am doing wrong

#

Oh so apparently, it works alright without object.values

#

But if I do object.values, I get the bottom result

#

unlike what you showed in the example

#

oh fuck

#

fuck me

#

pls

molten epoch
#

Object.keys returns the key of the object, in your case that would be the team names. Object.values returns the values of those keys, that would be the ..

#

I think you got it :p

stray oracle
#

I am such a dumass

#

;-;

#

i am sorry Matty and Michael

#

forgive me for i sin