【问题标题】:How to search and return json object?如何搜索并返回 json 对象?
【发布时间】:2021-02-05 21:43:44
【问题描述】:

我需要在 json children 值之后搜索并返回一个 json 对象 children。

这是我编写的工作代码(带回正确的对象):

const sites = [
  {
    name: "Lightinthebox WW",
    site_url: "https://lightinthebox.com/",
    domain: "lightinthebox.com",
  },
  {
    name: "Aliexpress WW",
    site_url: "https://aliexpress.com/",
    domain: "aliexpress.com",
  },
  {
    name: "Dx WW",
    site_url: "http://dx.com/",
    domain: "dx.com",
  }
];

var site = "aliexpress.com";
const foundSite = sites.find(s => site.includes(s.domain)); 
//return: {name: "Aliexpress WW", site_url: "https://aliexpress.com/",    domain: "aliexpress.com"}

现在,我有一个不同的 JSON:

const sites = {"All":{"5631":{"id":5631,"name":"Lightinthebox WW","site_url":"https:\/\/lightinthebox.com\/","domain":"lightinthebox.com"},"6115":{"id":6115,"name":"Aliexpress WW","site_url":"https:\/\/aliexpress.com\/","domain":"aliexpress.com"},"7077":{"id":7077,"name":"Dx WW","site_url":"http:\/\/dx.com\/","domain":"dx.com","13318":{"id":13318,"name":"GearBest WW","site_url":"https:\/\/gearbest.com\/","domain":"gearbest.com"}}};

我尝试做同样的事情,但我有“sites.find 不是函数”

你知道为什么吗?试图寻找一种方法来带回正确的对象(搜索 domain:"aliexpress.com" 然后带回所有对象 "{"id":6115,"name":"Aliexpress WW","site_url":"https ://aliexpress.com/","domain":"aliexpress.com"}")

谢谢

【问题讨论】:

  • 没有 JSON 对象这样的东西。 JSON 是一种字符串格式。一旦你用JSON.parse() 将它解析回一个对象,你就只有一个普通的旧对象。
  • 这是一个 JSON 对象,不需要解析,因为它不是字符串,我错过了什么?
  • 再说一次,没有 JSON 对象这样的东西。 JSON是一个字符串,一个对象是一个对象。
  • 您的问题只是 .find() 是一个数组方法,因此您的第一个示例有效。但是您的第二个示例是 Object 并且对象没有 .find() 方法。

标签: javascript json find


【解决方案1】:

Array.prototype.find() 是一个数组方法,在您的第一个示例中可以在 sites 上使用,因为它是一个数组,但在您的第二次尝试中,您试图在一个对象上调用它。

在这种情况下,您可以使用Object.values() 在顶级对象的All 属性内返回一个值对象数组,并在其上使用.find()

(这与JSON 无关,但知道您正在处理的类可用的方法;在这种情况下ArrayObject

const sites = {
  "All": {
    "5631": {
      "id": 5631, "name": "Lightinthebox WW", "site_url": "https:\/\/lightinthebox.com\/", "domain": "lightinthebox.com"
    },
    "6115": {
      "id": 6115, "name": "Aliexpress WW", "site_url": "https:\/\/aliexpress.com\/", "domain": "aliexpress.com"
    },
    "7077": {
      "id": 7077, "name": "Dx WW", "site_url": "http:\/\/dx.com\/", "domain": "dx.com"
    },
    "13318": {
      "id": 13318, "name": "GearBest WW", "site_url": "https:\/\/gearbest.com\/", "domain": "gearbest.com"
    }
  }
};

const site = "aliexpress.com";
const foundSite = Object.values(sites.All).find(s => site.includes(s.domain));

console.log(foundSite);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多