3

Given an object like this:

{
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
...
}

What is the simplest way to return this array:

[
   {value: "aaa", label: "Text1"},
   {value: "bbb", label: "Text2"}
]

Do I have to loop through the object? I thought there might be a way with Object.keys() and Object.values()

1
  • Please show what you've tried so far and explain what went wrong with your attempt (errors, unexpected results, etc.) Hint: Object.entries() could help here Commented Apr 16, 2019 at 15:47

5 Answers 5

2

You can use Object.entries to convert the object into an array. Use map to loop and return the desired object.

let obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
}

let result = Object.entries(obj).map(([k, v]) => ({value: k,label: v.text}));

console.log(result);

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

Comments

1

this can help

const obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
};
const ans = Object.keys(obj).map(itm => ({value: itm, title: obj[itm].text}))

console.log(ans);

Comments

1

You have to loop through those key values, use Object.entries method to get the key-value pair and Array#map method to iterate and generate the new array.

let data = {"aaa":{"text":"Text1","path":"Path1","type":"Type1"},"bbb":{"text":"Text2","path":"Path2","type":"Type2"}};

let res = Object.entries(data).map(([value, { text: title }]) => ({ value, title }))

console.log(res)

Comments

1

You can use for..in loop to iterate the object and push the value in an array

let obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  }
}
let modObj = [];

for (let keys in obj) {
  modObj.push({
    value: keys,
    label: obj[keys].text
  })
};

console.log(modObj)

Comments

0

Since no one mentioned using both Object.keys and Object.values as you mentioned in the question ...

var obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  }
};

var result = Object.keys(obj).map(function(key, i){
  return {value: key, label: Object.values(obj)[i].text}
});

console.log(result);

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.