0

I'm having some issues with returning a dynamic object. I'm using a react-native chart library, which requires me to return the data like so:

return [{
      'Manually Sold': { value: manuallySoldValue },
      'Trailing Stop Loss': { value: trailingStopLossValue },
      'Manual Short': { value: manualShortValue },
      'Profit': { value: profitValue },
      'Manual Buy': { value: manualBuy },
      'Strategy': { value: strategy },
      'Manual Close Short': { value: manualCloseShort },
      'available': { value: available },
      'in open positions': { value: inOpenPositions },
      'reserved': { value: reserved },
    }];

Which works fine, if the keys won't change.

StackedBarChart rendering:

stackedBarChart(counts, triggers) {
    return (
      <View>
        <StackedBarChart
          style={{ height: 10 }}
          colors={this.triggerColors()}
          contentInset={{ top: 30, bottom: 30 }}
          data={this.triggerValues(counts)}
          horizontal={true}
          keys={this.triggerKeys(counts)}
          valueAccessor={({ item, key }) => item[key].value}
        />
      </View>
    );
  }

this.triggerColors

triggerColors() {
  return ['#00c8c6', '#44baf1', '#c7e486', '#efdc6c'];
}

this.triggerKeys

triggerKeys(data) {
  return Object.keys(data);
}

Current implementation to build the required structure:

triggerValues(data) {
    // The trigger values can be a lot more, so this needs to be dynamic
    const keys = this.triggerKeys(data);
    let manuallySoldValue = '';
    let trailingStopLossValue = '';
    let manualShortValue = '';
    let profitValue = '';
    let manualBuy = '';
    let strategy = '';
    let manualCloseShort = '';
    let available = '';
    let inOpenPositions = '';
    let reserved = '';

    keys.map((key) => {
      switch (key) {
        case 'Manually Sold':
          manuallySoldValue = data[key];
          break;
        case 'Trailing Stop Loss':
          trailingStopLossValue = data[key];
          break;
        case 'Manual Short':
          manualShortValue = data[key];
          break;
        case 'Profit':
          profitValue = data[key];
          break;
        case 'Manual Buy':
          manualBuy = data[key];
          break;
        case 'Strategy':
          strategy = data[key];
          break;
        case 'Manual Close Short':
          manualCloseShort = data[key];
          break;
        case 'available':
          available = data[key];
          break;
        case 'in open positions':
          inOpenPositions = data[key];
          break;
        case 'reserved':
          reserved = data[key];
          break;
        default:
          break;
      }
    });

    return [{
      'Manually Sold': { value: manuallySoldValue },
      'Trailing Stop Loss': { value: trailingStopLossValue },
      'Manual Short': { value: manualShortValue },
      'Profit': { value: profitValue },
      'Manual Buy': { value: manualBuy },
      'Strategy': { value: strategy },
      'Manual Close Short': { value: manualCloseShort },
      'available': { value: available },
      'in open positions': { value: inOpenPositions },
      'reserved': { value: reserved },
    }];
  }

That would work if only the keys were set in stone. So I would like to build that part where the amount and keys won't matter. I've tried to build it with iteration over the data object (example objects below), but I can't seem to get the correct structure as mentioned below.

Example of data objects:

{available: "46.09", in open positions: "53.91", reserved: "0.00"}

-

{Manual Buy: 11, Manual Close Short: 7, Strategy: 42}

-

{Trailing Stop Loss: 3, Manual Short: 7, Profit: 46, Manually Sold: 5}

If you need any more information, please ask.

2 Answers 2

2

You can use the Object.keys function to get the list of object keys and iterate them to create the structure you want. Please see the sample code below.

const data = {
  "Trailing Stop Loss": 3,
  "Manual Short": 7,
  "Profit": 46,
  "Manually Sold": 5
};

const result = {};

Object.keys(data).forEach((key) => {
  result[key] = {
    value: data[key]
  };
});

console.log(result);

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

7 Comments

This will return [{…}, {…}, {…}, {…}], which is invalid to the lib. See my question for the required response.
@KevinEtore I have updated the code to follow the structure you want. My intent was to give you a direction on how to proceed.
This doesn't return the given output at all
@adiga The above code does not return anything since it is not written as a function. The code snippet just creates the required object structure in the result variable.
This gets you only the keys which are prsent in the data. Not all 10 keys mentioned in the output
|
1

Update:

You could reduce the entries of the data and create another object with a nested structure:

function triggerValues(data) {
  const output = Object.entries(data)
                       .reduce((r, [key, value]) => ({ ...r, [key]: { value } }), {});
    
  return [output]
}

console.log(triggerValues({available: "46.09", "in open positions": "53.91", reserved: "0.00"}))
console.log(triggerValues({"Manual Buy": 11, "Manual Close Short": 7, Strategy: 42}))

You can create an array of default keys and use simple for...of and for...in loops

function triggerValues(data) {
  const defaultKeys = [
    "Manually Sold",
    "Trailing Stop Loss",
    "Manual Short",
    "Profit",
    "Manual Buy",
    "Strategy",
    "Manual Close Short",
    "available",
    "in open positions",
    "reserved"
  ];

  const output = {};

  for (const key of defaultKeys) {
    if (key in data)
      output[key] = { value: data[key] }
    else
      output[key] = { value: '' }
  }

  return [output]
}

console.log(triggerValues({available: "46.09", "in open positions": "53.91", reserved: "0.00"}))
console.log(triggerValues({"Manual Buy": 11, "Manual Close Short": 7, Strategy: 42}))

8 Comments

I like this implementation, but I kind of want an implementation without a default object. Because there are a lot of default keys, and I don't want to write them all out.
@KevinEtore you gotta define the keys somewhere. An array of keys would work too.
I was afraid of that.. At least the spread syntax makes it cleaner
@KevinEtore What exactly do mean by "dynamically build object"? How can you build an object without knowing what keys to add. You can either get it from a config or from database. You have to have it defined somewhere. I have added another approach with with an array of keys.
I guess I wasn't that clear in my explanation, sorry for that. All the keys are available in my data object, So I can use Object.keys to fill up your defaultKeys.
|

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.