-1

I am trying to convert array of objects in to new object

I have this

const filter = [
    {
      fieldName: "userid"
      fieldValue: "12345"
    },
    {
      fieldName: "username"
      fieldValue: "myname"
    }
];

Need output like this

   const filterOut = {
           userid: "12345",
           username: "myname"
    }
Kish
  • 3
  • 2
  • What about: out = filter[1] – drakeerv May 08 '21 at 18:55
  • Does this answer your question? [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Ivar May 08 '21 at 19:04

3 Answers3

2

You could use Array.prototype.reduce() like this:

const filter = [
    {
      fieldName: "userid",
      fieldValue: "12345"
    },
    {
      fieldName: "username",
      fieldValue: "myname"
    }
];

const filterOut = filter.reduce((acc, { fieldName, fieldValue }) => ({ ...acc, [fieldName]: fieldValue }), {});

console.log(filterOut);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

Math the array to an array of [key, value] entries, and convert the entries to an object using Object.fromEntries():

const filter = [{"fieldName":"userid","fieldValue":"12345"},{"fieldName":"username","fieldValue":"myname"}];

const filterOut = Object.fromEntries(
  filter.map(o => [o.fieldName, o.fieldValue])
);

console.log(filterOut);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

A simple function to do this conversion:

function fieldArrayToObject(fields) {
  if (Array.isArray(fields)) {
     let obj = {};
     fields.forEach(field => {
       obj[field.fieldName] = field.fieldValue;
     });
     return obj;
  }
  return null;
}
Bar
  • 1,334
  • 1
  • 8
  • 21