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

4
  • 1
    Your output you want is an object, but for some reason you defined it as an array? Commented Feb 2, 2021 at 22:06
  • 1
    What is an Array -- What is an Object Commented Feb 2, 2021 at 22:06
  • What are facility_name and id? Can you show what result you're trying to get? Commented Feb 2, 2021 at 22:07
  • See stackoverflow.com/questions/17832583/… Commented Feb 2, 2021 at 22:10

2 Answers 2

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

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

Comments

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.

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.