0

I am using an object in my react-redux app in reducer file.The object is like as below

tradings: {
        'buy': {
            data: []
        },
        'sell': {
            data: []
        },
        'total': {
            data: []
        }
    },

So,whenever i get a new dataset i want to push it into data array of any object ,Suppose i got buy and data:[time:234234, amount: 0.0123 ].So my new tradings object will look like this:

tradings: {
        'buy': {
            data: [[time:234234, amount: 0.0123 ], ....]
        },
        'sell': {
            data: []
        },
        'total': {
            data: []
        }
    },

How can i concat arrays into this array in object?

5
  • array1.concat(array2) ? Commented Sep 5, 2019 at 16:26
  • tradings.buy.data.push(yourData); or tradings[key].data.push(yourData); where key is a string var Commented Sep 5, 2019 at 16:30
  • 1
    [time:234234, amount: 0.0123 ] is not a valid array in JS. It should be an object if you want key-value pairs like {time:234234, amount: 0.0123 }. Why not using Array.push() btw? Maybe with switch/case to act based on buy/sell type? Commented Sep 5, 2019 at 16:31
  • push can't be used here unless you make a copy before, as the question is related to redux you need to keep care of mutablity Commented Sep 5, 2019 at 16:33
  • @CodeManiac you're right. Maybe OP can use spread operator to copy the object since it holds primitive values. tradings.buy.data = [...tradings.buy.data, newData] may help Commented Sep 5, 2019 at 16:41

2 Answers 2

1

Assuming you have the following object:

tradings = {
        'buy': {
            data: []
        },
        'sell': {
            data: []
        },
        'total': {
            data: []
        }
    }

And your received data was:

data = {buy: {time:234234, amount: 0.0123 }}

You'll first need to grab the key in your data object and then push it to the desired array in your tradings object like the following:

key = Object.keys(data)[0];
tradings[key].data.push(data[key]);

fiddle: https://jsfiddle.net/9hsvd5pk/

Sign up to request clarification or add additional context in comments.

2 Comments

SO, from the next time?
This is a generalized solution that should work for all cases where the key does actually exist. Just make sure your data is structured correctly and this should always work. Check my fiddle.
0
tradings["buy"].data.push( YOUR ARRAY HERE )

to add arrays into that array, or create the array somewhere and add it via javascript :

tradings["buy"].data =  YOUR ARRAY HERE 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.