DharmikSoni
DharmikSoni

Reputation: 59

create array of object from array of strings

I am trying to solve one issue in my code, so if anyone can help me here?

I have some values added below, So i have one array of string values, which has mac addresses and min & max which is constant values. I am trying to map over macValue and trying to create array of object as given sample below, but unfortunately getting some error there. If anyone can help me out here.

please check here i am trying to dynamically add property inside map.

let macValue = ["MO-CK-DR-01","02","03"]
let min = true
let max = true

// code i have tried
 var print = macValue.map((item, i) => {
      (item['macAddress'] = item), (item.minimum = min), (item.maximum = max);
      return item;
    });

trying to create array of object like this

[
    {
      macAddress: value, //01
      mimimum: min,
      maximum: max,
    },
    {
      macvalue: value, // 02
      mimimum: min,
      maximum: max,
    },
]

but didn't work and getting this error enter image description here

Upvotes: 2

Views: 78

Answers (4)

Nikhil Patil
Nikhil Patil

Reputation: 2540

As you mentioned, the properties are dynamic, I have used string properties. This should work -

let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;

const result = macValue.map((value) => ({
  'macAddress': value,
  'minimum': min,
  'maximum': max
}));

console.log(result);

Upvotes: 0

Sarun UK
Sarun UK

Reputation: 6736

let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;

const output = macValue.map(value => ({
  macValue: value,
  minimum: min,
  maximum: max
}));

console.log(output);

Upvotes: 0

michael
michael

Reputation: 4173

let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;

const result = macValue.map((value) => ({
  macValue: value,
  minimum: min,
  maximum: max
}));

console.log(result);

Upvotes: 0

Goran.it
Goran.it

Reputation: 6299

As simple as:

let macValue = ["MO-CK-DR-01","02","03"]
let min = true
let max = true

const obj = macValue.map((value) => ({
  macvalue: value,
  minimum: min,
  maximum: max,
}))

Upvotes: 1

Related Questions