0

I have a ridiculous object like this.

{
order: ["a1","a2","a3","a4"],  
posts: {
a1: {id: "a1",message: "This is a1"},
a4: {id: "a4",message: "This is a4"},
a3: {id: "a3",message: "This is a3"},
a2: {id: "a2",message: "This is a2"},
}
}

I need to get "message" value from "posts" object with the order that define in "order" array. I can foreach the "order" array, but how to know when I have "a1" string, I need to take "a1" object in "posts" object?

Thank you!

1
  • 2
    const str = 'a1'; obj.posts[str] ??? It's not clear what you're asking Commented Sep 30, 2018 at 7:58

2 Answers 2

7

All you have to do is map over the order array and return the object based on keys using brackets notation like

const data = {
order: ["a1","a2","a3","a4"],  
posts: {
a1: {id: "a1",message: "This is a1"},
a4: {id: "a4",message: "This is a4"},
a3: {id: "a3",message: "This is a3"},
a2: {id: "a2",message: "This is a2"},
}
}

const res = data.order.map((id) => {
    return data.posts[id];
})

console.log(res);

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

Comments

0

Hope below code may help.

const data = {
order: ["a1","a2","a3","a4"],  
posts: {
a1: {id: "a1",message: "This is a1"},
a4: {id: "a4",message: "This is a4"},
a3: {id: "a3",message: "This is a3"},
a2: {id: "a2",message: "This is a2"},
}
}

Object.entries(data.order).forEach(([key, val]) => {
    console.log(data.posts[val]);          
});

4 Comments

Why do you suggest to write Object.entries(data.order).forEach(([key, val]) => { instead of simply writing data.order.forEach( val => {? What is the reason for using Object.entries and destructing here?
1) there was no specific reason for keeping key. 2) I used Object.entries, because it fits properly for the questioner expectation to access posts values in order by order.
I tried your idea with forEach order and get posts[value]. It can work too. I didn't know we can use posts[id] when posts is not an array.
For 2. then you should definitily not use Object.entries() because [...]the Object.entries() method returns[...]in the same order as that provided by a for...in loop and for...in [...]for...in should not be used to iterate over an Array [...]There is no guarantee that for...in will return the indexes in any particular order. so the order is not guaranteed for your code.

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.