0

Hellp every body hope all are good today ? I need some help please ...

This is my JSON with const = result :

[
 { asset: 'USDT', free: '35.00', locked: '0' },
 { asset: 'USDC', free: '80.99', locked: '0' },
 { asset: 'ETH', free: '0.005', locked: '0' },
]

If i do result[0].free = (USDT) 35.00 or result[2].free = (ETH) 0.005

How can i get free of asset name if i always define before, without enter the number manually?

I mean something like : result.asset['USDC'].free need return > 80.99

Because if i add different currency the position gonna change and number need to change too ... :/

How can i return the good free choosed please ?

Sincerely

1 Answer 1

1

You can format your JSON data from an array of objects to a nested object. You can achieve the same using Javascript, like this:

const result = [
    { asset: 'USDT', free: '35.00', locked: '0' },
    { asset: 'USDC', free: '80.99', locked: '0' },
    { asset: 'ETH', free: '0.005', locked: '0' }
];

const new_result = { asset: {} };

// Loop through the result array and structure the new_result object
result.forEach(item => {
    const { asset, free, locked } = item;
    new_result.asset[asset] = { free, locked };
});

// Formatted result as nested JSON
console.log(new_result);

// Accessing free and locked fields for USDT
console.log(new_result.asset['USDT'].free); // Output: 35.00
console.log(new_result.asset['USDT'].locked); // Output: 0

// Accessing free and locked fields for USDC
console.log(new_result.asset['USDC'].free); // Output: 80.99
console.log(new_result.asset['USDC'].locked); // Output: 0

// Accessing free and locked fields for ETH
console.log(new_result.asset['ETH'].free); // Output: 0.005
console.log(new_result.asset['ETH'].locked); // Output: 0

1
  • Thanks you so much its work SINCERELY really dear friends thanks you !! i'm asking if there is another way without forEach ? to make the code shortest ... ;D
    – forexmp45
    Mar 26 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.