Home > Back-end >  Match values from two array into a new array using id
Match values from two array into a new array using id

Time:07-18

So I have an array that has this structure

[{id:'bitcoin', change:-5.5}]

Again I have another array that has cryptos in this format

[{
            id: 'bitcoin',
            symbol: 'BTC',
            name: 'Bitcoin',
            img: 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/1200px-Bitcoin.svg.png',
            addr: '0xECe365B379E1dD183B20fc5f022230C044d51404'
        },]

That is just but an example, the arrays have multiple data objects. I am transforming the crypto array into a new array because I am calculating their real-time market price using each coin address like this

for (let i = 0; i < this.assets.length; i  ) {
            coinValue = await getPrice(this.assets[i].addr);
            this.transformedAssets.push({
                id: this.assets[i].id,
                symbol: this.assets[i].symbol,
                name: this.assets[i].name,
                img: this.assets[i].img,
                addr: this.assets[i].addr,
                value: numberWithCommas(coinValue)
            });
        }

Now I also want to pass coin_24h_percentage_change to the new array because the crypto array and the percentage change array have common id that can link them together but I am stranded on how to do that

I did something like this but its not working How am I suppose to make this happen

for (let i = 0; i < this.assets.length; i  ) {
            coinValue = await getPrice(this.assets[i].addr);
            const price_change_percentage_24h = JSON.parse(JSON.stringify(this.coinPerfomance[0].change));
            window.console.log(price_change_percentage_24h);
            this.transformedAssets.push({
                id: this.assets[i].id,
                symbol: this.assets[i].symbol,
                name: this.assets[i].name,
                img: this.assets[i].img,
                addr: this.assets[i].addr,
                daychange: this.coinPerfomance[this.assets[i].id].change,
                value: numberWithCommas(coinValue)
            });
        }

CodePudding user response:

You can try something like this :

let priceChange = [{id:'bitcoin', change:-5.5}];

let data = [
    {
        id: 'bitcoin',
        symbol: 'BTC',
        name: 'Bitcoin',
        img: 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/1200px-Bitcoin.svg.png',
        addr: '0xECe365B379E1dD183B20fc5f022230C044d51404'
    }
];


let result = data.map(el => ({...el, 'change': priceChange.find(pc => pc.id == el.id).change}));
console.log(result);
  • Related