简体   繁体   English

使用 find Function NativeJS 仅返回 JSON 数据的指定属性

[英]Returning only Specified attributes of JSON data using find Function NativeJS

So I'm new to react native and am trying to return a single attribute of JSON data.因此,我对本机反应很陌生,并试图返回 JSON 数据的单个属性。 I'm calling the CoinMarketCap API into a list of coin names, and when you click on the name it'll send you to a different page with a list of various attributes of the coin you clicked on.我将 CoinMarketCap API 调用到硬币名称列表中,当您单击名称时,它会将您发送到另一个页面,其中包含您单击的硬币的各种属性列表。 For example if you clicked on Ethereum, it'll show you the current price ($1,754), the symbol (ETH), the change in the last hour (-6.4%), etc. I'm using the find function to find the passed variable id name of the clicked coin.例如,如果您点击以太坊,它会显示当前价格 ($1,754)、交易品种 (ETH)、最近一小时的变化 (-6.4%) 等。我正在使用查找功能来查找传递点击硬币的变量 id 名称。 However when I return the data it prints the entire JSON data for that coin but I only want it to return specified attributes.但是,当我返回数据时,它会打印该硬币的整个 JSON 数据,但我只希望它返回指定的属性。

return JSON.stringify(Variables.LIST2.find(id => id.id == authorID));

Here's an example of what I mean with fruits这是我对水果的意思的一个例子

const fruits = [

{name: 'bananas', quantity: 2, color: 'yellow'},
{name: 'apples', quantity: 3, color: 'red'},
{name: 'grapes', quantity: 5, color: 'purple'},
];

const result = fruits.find( ({ name }) => name === 'apples' );
console.log(result) // output: { name: 'apples', quantity: 3, color: 'red'}

What would I do if I only wanted to return the name and the color instead of name quantity and color?如果我只想返回名称和颜色而不是名称数量和颜色,我该怎么办?

I've tried using parse but I still need to use find to locate the id from the passed navigation variable.我试过使用parse但我仍然需要使用find从传递的导航变量中找到 id。 What should I do?我应该怎么办?

// output: { name: 'apples', color: 'red'}

const fruits = [
    {name: 'bananas', quantity: 2, color: 'yellow'},
    {name: 'apples', quantity: 3, color: 'red'},
    {name: 'grapes', quantity: 5, color: 'purple'},
];  
const result = fruits.find( ({ name }) => name === 'apples' );
//console.log(result)
var obj = {name: result.name, color: result.color}

console.log(obj);

Hey, As far I know, we can't return object with specified attributes, So we have to go in a hardcoding way like I did.嘿,据我所知,我们不能返回具有指定属性的对象,所以我们必须像我一样采用硬编码方式。 I hope it will be helpful for you.我希望它对你有帮助。

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

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