简体   繁体   中英

How can I turn an array object into an object?

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'}

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)

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);

i would use reduce.. ex:

const answer = hello.reduce((prev, cur) => {
  prev[cur.value] = cur.label;
  return prev;
}, {});

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM