【问题标题】:Node.js/express parsing data and still getting back [object Object] in response and some data is missingNode.js/express 解析数据并仍然返回 [object Object] 作为响应并且缺少一些数据
【发布时间】:2017-09-21 17:24:32
【问题描述】:

如上所述,我正在使用 NODE/Express 后端并尝试在将数据发送到前端之前解析出一些数据。

我有一个对象(项目)数组,想解析出每个项目中的某个字段,尤其是descriptiongeolocation。看起来它工作得很好,但我遇到了几个问题。

首先,我将向您展示其中一个项目,以向您展示它之前的内容:

{
    "_id": {
        "$oid": "59925302e12872a81b28099e"
    },
    "offer": "19f5d9ef37b30311",
    "txid": "389eb024f8869d787954c74d1653b8358e581cb4c81358361ffac662875bceec",
    "expires_in": 13770133,
    "expires_on": 1516531809,
    "expired": false,
    "height": "46411",
    "category": "for sale",
    "title": "Jack Garratt Signed Deluxe CD",
    "quantity": "1",
    "currency": "USD",
    "sysprice": 415240000000,
    "price": "35.00",
    "ismine": false,
    "commission": "0",
    "offerlink": "false",
    "private": "No",
    "paymentoptions": 2,
    "paymentoptions_display": "BTC",
    "alias_peg": "sysrates.peg",
    "description": "{\"description\":\"Signed, near mint double CD Only played a very few times\",\"media\":{\"defaultIdx\": 0,\"mediaVault\": [{\"mediaType\":\"img\",\"mediaURL\":\"http://i.imgur.com/bB7QjDR.jpg\"}]}}",
    "alias": "Signed, near mint double CD Only played a very few times http://i.imgur.com/bB7QjDR.jpg",
    "address": "1GR389Tki2LS3jScFUhrVxVnXdPdED5839",
    "alias_rating_display": "0.0/5 (0 Votes)",
    "offers_sold": 0,
    "geolocation": "{\"coords\":{\"lat\":36.8518706,\"lng\":-123.5029326}}",
    "alias_rating_count": 0,
    "alias_rating": 0,
    "safetylevel": 0,
    "safesearch": "Yes",
    "offerlink_seller": "",
    "offerlink_guid": "",
    "time": {
        "$date": "1970-01-18T04:29:58.326Z"
    },
    "cert": "",
    "__v": 0
}

接下来我将向您展示我如何解析我想要的数据。我特别想要一个description geolocation 和一个新字段media

  let newResults = [];
  let updatedItem = {};
  results.map((item, i) => {
    const newDescription = JSON.parse(item.description);
    const newGeolocation = JSON.parse(item.geolocation);
    console.log(newGeolocation)
    updatedItem = item;
    updatedItem.geolocation = newGeolocation;
    updatedItem.media = newDescription.media;
    updatedItem.description = newDescription.description;

    newResults.push(updatedItem);

    return newResults;
  });

  console.log(newResults[24]);

这是console.log(newResults[24])的结果:

{ _id: 59925302e12872a81b2809a3,
  offer: '17fff08820c6da06',
  txid: 'f27ec82c4cd694ecfdf061ebff7709a6154e39767595f7da08e4b2a40503c816',
  expires_in: 26828208,
  expires_on: 1529589884,
  expired: false,
  height: '276435',
  category: 'for sale',
  title: 'Marijuana Flavoured Vape E-Liquid 10ml 6mg',
  quantity: '19',
  currency: 'GBP',
  sysprice: 1912000000,
  price: '2.00',
  ismine: false,
  commission: '0',
  offerlink: 'false',
  private: 'No',
  paymentoptions: 1,
  paymentoptions_display: 'SYS',
  alias_peg: 'sysrates.peg',
  description: 'Marijuana Flavoured E-Liquid 10ml 6mg',
  alias: 'Marijuana Flavoured E-Liquid 10ml 6mg',
  address: '1DNeg3CrRFx6PuLcCry26p9y2XiTzTTFqw',
  alias_rating_display: '0.0/5 (0 Votes)',
  __v: 0,
  offers_sold: 0,
  geolocation: '[object Object]',
  alias_rating_count: 0,
  alias_rating: 0,
  safetylevel: 0,
  safesearch: 'Yes',
  offerlink_seller: '',
  offerlink_guid: '',
  time: Sun Jan 18 1970 02:32:37 GMT-0600 (Central Standard Time),
  cert: '' }

如您所见,数据似乎已针对描述进行了解析,但地理位置给了我一个奇怪的[object Object],即使我将它控制台记录在地图中,它也会为我提供每个解析的数据并且它们看起来美好的。

我想在这里指出的其他一点是媒体字段甚至不存在。但是,如果我要去console.log(newResults[24].media),它会向我显示解析后的数据。但是,如果我确实尝试像item.media 这样在前端访问它,我会得到未定义的结果,这是预期的,因为它没有显示出来。

【问题讨论】:

  • 我注意到您正在使用.map,但您没有使用它的返回值(看起来只是newResults 数组的数组)。在我看来,您可以在每次映射迭代中return updatedItem,然后将newResults 分配给映射数组。这可能不是您问题的核心,但它会使代码更清晰和/或更容易理解。谢谢!
  • 我这样做是为了清理它,感谢那个帮手。但是仍然需要帮助来解决问题。
  • 什么定义了newGeolocation?显然这样做不正确
  • JSON.parse(item.geolocation) 是它的定义。

标签: javascript node.js parsing express


【解决方案1】:

您误用了map()map() 会从中返回一个对象。尝试使用这样的东西:

let newResults = results.map((item, i) => {
    const {
        media,
        description
    } = JSON.parse(item.description);

    const geolocation = JSON.parse(item.geolocation);

    return {
        geolocation,
        media,
        description
    };
});

console.log(newResults[24]);

如果您想将这些属性附加到项目上(不改变原始项目),您可以使用Object.assign() 它将对象的所有属性从第二个参数转储到第一个参数的优先级中后面的论点。

换句话说,我们要将调用返回的值返回给Object.assign({}, item, {...new props...}),并且该调用将创建一个新对象{},然后将item中的所有属性转储到该新对象中,然后它将在第一个 {} 参数上转储来自 {...new props...} 的所有属性,如果属性已经存在,它将覆盖它们。

let newResults = results.map((item, i) => {
    const {
        media,
        description
    } = JSON.parse(item.description);

    const geolocation = JSON.parse(item.geolocation);

    return Object.assign({}, item, {
        geolocation,
        media,
        description
    });
});

此外,当在 node.js 中使用 console.log() 打印嵌套对象时,node 将截断输出而不是打印整个数组。考虑这段代码:

let tmp = [
    {
        foo: "Bar",
        fizz: [
            {
                buzz: "hello"
            }
        ]
    }
];

console.log(tmp);

将打印:

[ { foo: 'Bar', fizz: [ [Object] ] } ]

对象仍然没问题,如果您尝试使用console.log(tmp[0].fizz[0].buzz); 取消引用嵌套对象本身,您将得到输出:hello

【讨论】:

  • 这确实有效,但是我仍然需要上一个原始项目中的所有其他字段。
  • 我得到了一些奇怪的功能。它现在有原始字段,最后是:pres: { save: [ [Object], [Object], [Object] ] }, _posts: { save: [] }, save: { [Function] numAsyncPres: 0 }, geolocation: { coords: { lat: 46.6117304, lng: -121.8207893 } }, media: { defaultIdx: 0, mediaVault: [ [Object] ] }, description: 'Marijuana Flavoured E-Liquid 10ml 6mg' }
  • 它好像没有覆盖它们。
  • 什么意思?如果您问为什么会看到“[Object]”,请查看我的新编辑。
  • 没有没有。我的意思是我要取回full original item,然后在项目的末尾,它现在有所有更新的字段,但在更新字段之前有一个_pres_postssave 字段我们添加的。他们没有取代其他人。虽然我非常肯定这是你会这样做的,所以我不知道。
【解决方案2】:

试试

results.map((item, i) => {
  const newDescription = JSON.parse(item.description);
  const newGeolocation = JSON.parse(item.geolocation);
  console.log(newDescription.media)
  updatedItem = item;
  updatedItem.geolocation = item.geolocation; //just assign geolocation
  updatedItem.media = JSON.stringify(newDescription.media); //stringify the media object
  updatedItem.description = newDescription.description;

  newResults.push(updatedItem);

  return newResults;
});

【讨论】:

  • media 字段仍然没有显示,我需要解析 geolocation,所以这不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2021-01-14
  • 2018-02-07
  • 1970-01-01
相关资源
最近更新 更多