Home > OS >  i want to push the coin name in a new array with object where free is greater than 1
i want to push the coin name in a new array with object where free is greater than 1

Time:03-05

I want to use the json data to get an object from the json object where free has value greater than 0 and push that whole object in a new array which i got by using (Object.values ) which i mentioned below but i also want to push coin name in the new array for example i want to push "name": "BIT" in {"free": 1, "used": 0,"total": 0, "usd_price": 0,} and get a result like this [{"name": "BIT", "free": 1, "used": 0,"total": 0, "usd_price": 0},{name": "BTC", "free": 1, "used": 0,"total": 0, "usd_price": 0}]

const json = {
    "success": true,
    "messsage": "",
    "data": {
        "BIT": {
            "free": 0,
            "used": 0,
            "total": 0,
            "usd_price": 0,
            "usd_val": 0,
            "percent_change_24h": 0,
            "usd_pnl_24h": 0,
            "name": "",
            "logo": "https://www.trailingcrypto.com/assets/img/default-coin.png",
            "portfolio_share": 0
        },
        "BTC": {
            "free": 0,
            "used": 0,
            "total": 0,
            "usd_price": 38400.82298054895,
            "usd_val": 0,
            "percent_change_24h": 0,
            "usd_pnl_24h": 0,
            "name": "Bitcoin",
            "logo": "https://s2.coinmarketcap.com/static/img/coins/128x128/1.png",
            "portfolio_share": 0
        },
        "DOT": {
            "free": 0,
            "used": 0,
            "total": 0,
            "usd_price": 20.07605927484185,
            "usd_val": 0,
            "percent_change_24h": 0,
            "usd_pnl_24h": 0,
            "name": "Polkadot",
            "logo": "https://s2.coinmarketcap.com/static/img/coins/128x128/6636.png",
            "portfolio_share": 0
        }
    }
}



Object.values(json.data).map((item) => {
        if (item?.free >= 1) {
          ret_arr.push(item);
        }
        }
        else if(item?.free > 0){
                ret_arr.push(item);     
            }
     });

CodePudding user response:

You can use Object.entries to get the key and value, filter it, and then construct the new elements from the keys and values.

const free = Object.entries(json.data)
  .filter(([k, v]) => v.free > 0)
  .map(([k, v]) => ({name: k, ...v}));

CodePudding user response:

const first = Object.entries(data)
        .filter(([k, v]) => v.free_usd_val >= 1)
        .map(([k, v]) => ({newName: k, ...v}));
    
    const second = Object.entries(data)
        .filter(([k, v]) => v.free_usd_val > 0)
        .map(([k, v]) => ({newName: k, ...v}));
    
        if(checkedValue == true){ 
            return first;
        }
    
        else {
            return second;
    

}
  • Related