【发布时间】: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