2

There is an object array like this:

const schema = [
    { placeholder: 'Title', name: 'title' },
    { placeholder: 'Authors', name: 'author' },
    { placeholder: 'Publisher',  name: 'publisher', optional: true },
    { placeholder: 'Edition', name: 'edition', optional: true }
]

Now I would like to get an object with all name fields as key with 1 value:

result = { 'title': 1, 'author': 1, 'publisher': 1, 'edition': 1 }

I tried to use map, but

schema.map(o => { return o.name })

gives me just an array:

['title', 'author', 'publisher', 'edition']

5 Answers 5

5

You need reduce

const schema = [
    { placeholder: 'Title', name: 'title' },
    { placeholder: 'Authors', name: 'author' },
    { placeholder: 'Publisher',  name: 'publisher', optional: true },
    { placeholder: 'Edition', name: 'edition', optional: true }
]

console.log(schema.reduce((acc, {name}) => (acc[name] = 1, acc), {}))

Sign up to request clarification or add additional context in comments.

Comments

3

const schema = [
    { placeholder: 'Title', name: 'title' },
    { placeholder: 'Authors', name: 'author' },
    { placeholder: 'Publisher',  name: 'publisher', optional: true },
    { placeholder: 'Edition', name: 'edition', optional: true }
];

console.log(schema.reduce((acc, current) => {
  acc[current.name] = 1;
  
  return acc;
}, {}));

Comments

3

You could use Object.assign and the spread syntax:

Object.assign(...schema.map(o => ({ [o.name]: 1 })));

const schema = [
    { placeholder: 'Title', name: 'title' },
    { placeholder: 'Authors', name: 'author' },
    { placeholder: 'Publisher',  name: 'publisher', optional: true },
    { placeholder: 'Edition', name: 'edition', optional: true }
];

const result = Object.assign(...schema.map(o => ({ [o.name]: 1 })));
console.log(result);

2 Comments

The most ESNexty answer :)
@YuryTarabanko, thanks for the appreciation, but strictly speaking this only uses ES2015 features (Object.assign, ..., =>, object literals with dynamic property names).
1

You can first create an object and the use forEach loop to add properties.

const schema = [
  { placeholder: 'Title', name: 'title' },
  { placeholder: 'Authors', name: 'author' },
  { placeholder: 'Publisher',  name: 'publisher', optional: true },
  { placeholder: 'Edition', name: 'edition', optional: true }
]

var obj = {}
schema.forEach(o => obj[o.name] = 1)
console.log(obj)

Comments

0

.map will always give you an array. Since you want to convert you array of objects to single object, it makes sense to use .reduce instead.

schema.reduce( (a, c) => {
  a[c.name] = 1;
  return a;
} , {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.