如何通过Javascript中的名称获取对象?

时间:2018-09-30 07:57:03

标签: javascript

我有一个这样的荒谬对象。

{
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"},
}
}

我需要从“ posts”对象中获取“ message”值,并在“ order”数组中定义顺序。我可以foreach“顺序”数组,但是如何知道当我有“ a1”字符串时,我需要在“ posts”对象中使用“ a1”对象吗?

谢谢!

2 个答案:

答案 0 :(得分:7)

所有您需要做的就是在order数组上进行映射,并使用方括号表示法基于键返回对象,

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

答案 1 :(得分:0)

希望以下代码会有所帮助。

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