简体   繁体   English

json 过滤 javascript api

[英]json filtering javascript api

Hello i have some problem with json filtration when i print jsonArray without id (jsonArray) prints the object to me normally but when i add.id (jsonArray.id) its says undefined What am I doing wrong?您好,当我打印不带 id 的(jsonArray)时,json 过滤有一些问题,通常会向我打印 object,但是当我 add.id (jsonArray.id)时,它说undefined我做错了什么?

the object i gets with jsonArray and i want to print only 'id' of it {id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}我使用 jsonArray 获得的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 is array not object. jsonArray 是数组而不是 object。 And getID is a async function. getID 是异步的 function。 It will return promise.它将返回 promise。 You need to call then to get result.你需要打电话然后得到结果。

 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));

It's because jsonArray here is a list and not a single object.这是因为这里的 jsonArray 是一个列表,而不是单个 object。

First check it's length to make sure there's atleast one object after the filter and log the first element via:首先检查它的长度以确保在过滤器之后至少有一个 object 并通过以下方式记录第一个元素:

if (jsonArray.length > 0) {
    console.log(jsonArray[0].id)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM