在JS中,尤其是在redux中,什么被视为普通对象?
例如以下内容也被视为普通对象吗?
let a = {
b: {
c: 'd'
}
};
Redux声明动作必须是简单的对象,但是如果过一会儿需要输入以下数据并将其添加到状态中,该怎么办?
let payload = {
all: ['john', 'jane'],
byId: {
john: {
name: 'john',
age: 23
},
jane: {
name: 'jane',
age: 40
}
}
}
我要采取行动:
function userLoad(payload) {
return { type: USER_LOAD, payload }
}
但是,如果有效载荷不是简单的对象,则这不是很好的实践。如何处理这种情况。
答案 0 :(得分:1)
好,所以它被视为普通对象,请参见下面的代码段。
var people = [{
name: "jon",
age: 42
}, {
name: "mary",
age: 32
}]
var result = people.map(o => Object.keys(o).map(string => `"${string}"`).join(' ')).join(', ');
console.log(result);
答案 1 :(得分:1)
普通对象或POJO(普通javascript对象)是通过以下方式创建的对象:
let foo = {prop1: 1} // object literal
let bar = new Object(); // new object syntax
与POJO和通过构造函数创建的对象的区别如下:
function Person (name) {
this.name = name;
}
let me = new Person('willem') // this object is not a POJO
console.log(Object.getPrototypeOf(me) === Person.prototype); // prototype is Person
let POJO = {};
console.log(Object.getPrototypeOf(POJO) === Object.prototype); // POJO prototype is always Object not the prototype property of the constructor functoin. This is the difference