I want to put an array object called hello into a constant called answer. At this time, I want to change the key value of the answer to the value key of hello and the value of the answer to the label value of hello.
how can i do that? i was thinking object entries but i couldn't do that.... is it possible??
this is my code
const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;
expected answer
const answer = {Tangerinefeed: 'one', dryexamfeed: 'two', wetfeed: 'three', sawdust: 'forth', etc: 'five'}
asked Jun 21, 2022 at 1:34
user15322469
9173 gold badges14 silver badges37 bronze badges
-
Object.fromEntries - and some codeBravo– Bravo2022年06月21日 01:41:08 +00:00Commented Jun 21, 2022 at 1:41
-
1What did you try? Obviously, you iterate the current array and add properties to an object while iterating.jfriend00– jfriend002022年06月21日 01:42:53 +00:00Commented Jun 21, 2022 at 1:42
4 Answers 4
You can use reduce to achieve it
const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;
const finalResult = hello.reduce((result, item) => {
result[item.value] = item.label
return result
}, {})
console.log(finalResult)
answered Jun 21, 2022 at 1:42
Nick Vu
15.6k5 gold badges29 silver badges37 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can do it with forEach method.
const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;
const answer = {};
hello.forEach(a=>{ answer[a.value]=a.label})
console.log(answer);
Comments
i would use reduce.. ex:
const answer = hello.reduce((prev, cur) => {
prev[cur.value] = cur.label;
return prev;
}, {});
Comments
Have you ever used a map?
Hope it helps you.
Thank you.
const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
]
let answer = {};
hello.map(h => {
answer[h.value] = h.label;
return true;
});
console.log(answer);
1 Comment
Community
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
lang-js