简体   繁体   中英

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. 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. 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. However when I return the data it prints the entire JSON data for that coin but I only want it to return specified attributes.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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