0

I am working on react native project.

In that, I am getting multiple data from api like following.

{
    Value: "895"
    Return: "2"
    Return1: "0.20"
    Return3: "0.40"
    Return5: "0.60"
    Return10: "0.50"
    StartDate: "2019-06-13"
}, {
    Value: "900"
    Return: "4"
    Return1: "0.10"
    Return3: "0.40"
    Return5: "0.70"
    Return10: "0.90"
    StartDate: "2019-06-14"
},

But, I am trying to take all Return data to some return array which I need to show each index of data into flatlist. But, Here I got confuse how to take it into another array because Return key has 1,3,5, etc at the ending of the key in each index.

const ValuesData = [];

if (ReturnsData) {
  ReturnsData.map((item, index) => {
    ValuesData.push({
     `${ReturnsData[index].Return`${index}`}`,
    });
  });
}

Can anyone suggest me how to take Return(1,3,5,10) data into array?

3
  • 1
    Can you create a runnable snippet? See how to create an minimal reproducible example Commented Mar 20, 2019 at 18:19
  • Just transform response (guess that reactjs has this option) to whatever you want to return. For returnX, you can iterate keys and all keys matching pattern push into result array.. Commented Mar 20, 2019 at 18:26
  • I am new to react native, Can you post any sample? Commented Mar 20, 2019 at 18:27

6 Answers 6

1

Use startWith with getOwnPropertyNames or Object.keys( your_object ).

var apiData = [{
    Value: "895",
    Return: "2",
    Return1: "0.20",
    Return3: "0.40",
    Return5: "0.60",
    Return10: "0.50",
    StartDate: "2019-06-13",
}, {
    Value: "900",
    Return: "4",
    Return1: "0.10",
    Return3: "0.40",
    Return5: "0.70",
    Return10: "0.90",
    StartDate: "2019-06-14",
}]

/* All values of each key thats starts with "Return" in flat array */
const valuesFlat = []
apiData.map( (it, idx) => 
	Object.getOwnPropertyNames(it).filter( prop => prop.startsWith("Return") )
	.map( name => apiData[idx][name]  )
	.forEach( its => valuesFlat.push(its) )
)
console.log( "Flat values" )
console.log( valuesFlat )

/* All values of each key thats starts with "Return", not flat array */
const values = apiData.map( (it, idx) => 
	Object.getOwnPropertyNames(it).filter( prop => prop.startsWith("Return") )
	.map( name => apiData[idx][name]  )
)
console.log("Values")
console.log(values)


const indexes = apiData.map( (it, idx) => 
	Object.getOwnPropertyNames(it)
	.map( (prop, idxs) => { if(prop.startsWith("Return")) return idxs} )
	.filter( prop => prop != undefined )
)
console.log("indexes")
console.log( indexes )



const indexesFlat = []

apiData.forEach( (it, idx) => 
	Object.getOwnPropertyNames(it)
	.map( (prop, idxs) => { if(prop.startsWith("Return")) return idxs} )
	.filter( prop => prop != undefined )
	.forEach( it => indexesFlat.push(it) )
)

console.log("Flat indexes")
console.log( indexesFlat )

const flatPropsWithValues = []
apiData.map( (it, idx) => 
	Object.getOwnPropertyNames(it)
	.filter( prop => prop.startsWith("Return") )
	.forEach( prop => flatPropsWithValues.push( { prop: prop, value: apiData[idx][prop] } ) )
)


console.log("Flat props with values")
console.log( flatPropsWithValues )

Log.d(TAG, "runON " + Thread.currentThread().getName());

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

Comments

0

Use a regex match and a loop instead:

const ValueData = [];
const re = new Regex('(Return[0-9]{1,2})');
if (ReturnsData) {
  for (const key in ReturnsData) {
    if (if ReturnsData.hasOwnProperty(key) && re.test(key)) {
      ValueData.push(ReturnsData[key]);
    }
  }
}

The regex should match any data starting with 'Return' and ending in one or two numbers. The for...in loop goes through the keys, checks if they exist on the object, and if they match the regex. If they do, the value of that key is added to ValueData.

Comments

0

Assumptions:

I am assuming your keys are always like Return, Return1, Return3, Return5 and Return10 and that your data is already stored in an array (named ReturnsData). In that case you could do the following:

var ValuesData = []; 
if (ReturnsData) {
  ValuesData = ReturnsData.map((item) => {
      return { item.Return, item.Return1, item.Return3, item.Return5, item.Return10 }; 
  });
}

Explanation:

The map function returns by default a new array. That's why we can store the new array directly in ValuesData. Inside the map function, we loop over your objects. Each object's element can then be accessed by item.YOUR_KEY. At the end we are returning a new object. Then the next object is being processed.

Comments

0

First, I think you would be better to use a forEach rather than map since you aren't aren't assigning that statement to a new array and aren't returning anything within the function body. Within the forEach you can iterate through each key and do a regex test to see if the key starts with "Return." If it does, then push the value associated with that key it into your ValuesData array.

let ValuesData = []

ReturnsData.forEach(item => {
    let reg = new RegExp(/^Return.*/)
    for (key in item) {
        if (reg.test(key)) {
            ValuesData.push(item[key]);
        }
    }
})

Which gives you the result:

["2", "0.20", "0.40", "0.60", "0.50", "4", "0.10", "0.40", "0.70", "0.90"]

This will no matter what number comes after Return. So you could have Return12, Return1345, Return76524, etc and still get the desired result.

Comments

0

The following should work :

const ValuesData = [];

if (ReturnsData) {
  ReturnsData.map((item, index) => {
    ValuesData.push({
      ReturnsData[index][`Return${index}`],
    });
  });
}

3 Comments

['Return${index}']}` --> Unexpected template string expression.eslint(no-template-curly-in-string)
Unexpected string concatenation.eslint(prefer-template)
I believe there are other better answers, I was just trying to fix the interpolated string for you, this isn't the right solution for what you want.
0

Returns an array of the values of the keys Return1, Return3, Return5, Return10:

const ReturnsData = {
  Value: "900",
  Return: "4",
  Return1: "0.10",
  Return3: "0.40",
  Return5: "0.70",
  Return10: "0.90",
  StartDate: "2019-06-14"
};

const regex = /Return(1|3|5|10)/;

const ValuesData = Object.entries(ReturnsData)
  .filter(([k, v]) => regex.test(k))
  .map(([k, v]) => v);

console.log(ValuesData);

1 Comment

I re-read the question and it looks like you only want Return1, Return3, Return5, Return10 included so I updated my answer.

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.