json过滤javascriptapi
json filtering javascript api
你好,我有一些关于 json 过滤的问题
当我打印 jsonArray without id (jsonArray)
正常打印对象给我但是当我添加 .id (jsonArray.id)
它说 undefined
我做错了什么?
我用 jsonArray
得到的对象,我只想打印它的 'id'
{id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele){
return ele.title == "8";
});
console.log(jsonArray.id)
}
getID();
因为这里的jsonArray是一个列表而不是一个对象
首先检查它的长度以确保在过滤器之后至少有一个对象并通过以下方式记录第一个元素:
if (jsonArray.length > 0) {
console.log(jsonArray[0].id)
}
jsonArray 是数组而不是对象。 getID 是一个异步函数。它会 return 承诺。你需要调用然后得到结果。
const api_url = 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele) {
return ele.title == "8";
});
const tmp_obj = {
id: jsonArray[0].id,
product_id: jsonArray[0].product_id,
title: jsonArray[0].title,
price: jsonArray[0].price
}
//console.log(tmp_obj)
return tmp_obj
}
getID().then(result => console.log(result));
你好,我有一些关于 json 过滤的问题
当我打印 jsonArray without id (jsonArray)
正常打印对象给我但是当我添加 .id (jsonArray.id)
它说 undefined
我做错了什么?
我用 jsonArray
得到的对象,我只想打印它的 'id'
{id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele){
return ele.title == "8";
});
console.log(jsonArray.id)
}
getID();
因为这里的jsonArray是一个列表而不是一个对象
首先检查它的长度以确保在过滤器之后至少有一个对象并通过以下方式记录第一个元素:
if (jsonArray.length > 0) {
console.log(jsonArray[0].id)
}
jsonArray 是数组而不是对象。 getID 是一个异步函数。它会 return 承诺。你需要调用然后得到结果。
const api_url = 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele) {
return ele.title == "8";
});
const tmp_obj = {
id: jsonArray[0].id,
product_id: jsonArray[0].product_id,
title: jsonArray[0].title,
price: jsonArray[0].price
}
//console.log(tmp_obj)
return tmp_obj
}
getID().then(result => console.log(result));