0

Hi I am looking to create an array that looks similar to this

const userList = {
  123: "Tom",
  124: "Michael",
  125: "Christin",
};

it contains both value and label, what I tried so far

let raw =  []
for (let x in data) {
  raw.push(data[x].facility_name : data[x].id)
}

but it didn't work because "," was expected, if someone can help please

Youssef
  • 565
  • 1
  • 5
  • 21
  • 1
    Your output you want is an object, but for some reason you defined it as an array? – epascarello Feb 02 '21 at 22:06
  • 1
    [What is an Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) -- [What is an Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) – Randy Casburn Feb 02 '21 at 22:06
  • What are `facility_name` and `id`? Can you show what result you're trying to get? – Barmar Feb 02 '21 at 22:07
  • See https://stackoverflow.com/questions/17832583/create-an-object-with-dynamic-property-names – Barmar Feb 02 '21 at 22:10

2 Answers2

2

You are confusing arrays and objects. You need to add a key to an object not push. I kept it as a for in loop, but a for of loop would make more sense.

const data = [
  { id: 1, facility_name: "foo1" },
  { id: 2, facility_name: "foo2" },
  { id: 3, facility_name: "foo3" }
];

let raw = {};
for (let x in data) {
  raw[data[x].id] = data[x].facility_name;
}

console.log(raw);

How I would code it using reduce.

var data = [
  { id: 1, facility_name: "foo1" },
  { id: 2, facility_name: "foo2" },
  { id: 3, facility_name: "foo3" }
];

const raw = data.reduce(function (acc, facility) {
  acc[facility.id] = facility.facility_name;
  return acc;
}, {})
console.log(raw);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

IF your data has nested objects then you might do this:

let raw = {};
for(x in data)
{
    raw[data[x].facility_name] = data[x].id;
}

This is useful when you want to get rid of duplicates.

Sedki Sghairi
  • 359
  • 2
  • 7