创建json对象以排除未定义的属性

时间:2016-07-10 20:01:02

标签: javascript firebase ecmascript-6 firebase-realtime-database

我有以下片段代码,它在一个循环中创建一个JavaScript对象,其中某些属性可能未定义:

reader.on('record', function(record) {

    let p = record.children;
    let player = {};

    // below we create a dynamic key using an object literal obj['name'], this allows use to use
    // the id as the firebase reference id.
    player[p[0].text] = {
        id: parseInt(p[0].text, 10) || "",
        name: p[1].text || "",
        country: p[2].text || ""
    };
};

我的问题因此;例如,通过“地图”创建此对象有更好的方法吗?如果属性未定义,则不要将它们添加到对象。

注意:此数据正在发送到Firebase数据库,因此任何未定义的值都会产生错误 - 我的粗略(但工作)方法是将它们添加为空字符串。

以下是我想看到的JSON示例(请注意第二位玩家不会遗漏国家/地区):

{
 "players" : {
    "100001" : {
      "id" : 100001,
      "name" : "Matt Webb",
      "country" : "ENG"
    },
    "100002" : {
      "id" : 100002,
      "name" : "Joe Bloggs",
    }
}

2 个答案:

答案 0 :(得分:3)

null值未在Firebase中设置,并且不会给您错误

player[p[0].text] = {
    id: parseInt(p[0].text, 10) || null,
    name: p[1].text || null,
    country: p[2].text || null
};

答案 1 :(得分:2)

您可以这样做:

player = JSON.parse(JSON.stringify(player));

这样,你可以使用......

player[p[0].text] = {
    id: parseInt(p[0].text, 10),
    name: p[1].text,
    country: p[2].text
};

...并且不用担心未定义的值,因为JSON.stringify没有使用未定义的值序列化键...