2

how to loop through this array , I want to loop and and add name value to an empty array , when I console .log it gives the results below, could you please help , the result of my code is empty array

this.props.names it shows

(3) [{…}, {…}, {…}] 0: {name: "abc", id: 1} 1: {name: "def", id: 2} 2: {name: "gh", id: 3} length: 3 proto: Array(0)

let titles = []
let cats = []
 cats = this.props.names
 let len = this.props.names.length;
 for( i = 0 ;i< cats.length ; i++){
    titles.push(cats[i].id)
 }

return titles;
7
  • 4
    1< cats.len should be i< cats.length but you can do it more readable with map: const titles=cats.map(cat=>cat.id) Commented Feb 8, 2019 at 15:23
  • its corrected , but still empty array as results Commented Feb 8, 2019 at 15:25
  • Try using length instead of len or even better; use the map. Commented Feb 8, 2019 at 15:26
  • could you please post some data samples ? EX : this.props.names=[a,b,c,d] and the expected and current result Expected result:[x,y,z]; current result : [e,r,t] Commented Feb 8, 2019 at 15:27
  • You could basically replace all the code posted here with return this.props.names.map(cat=>cat.id) Commented Feb 8, 2019 at 15:28

2 Answers 2

1

from what i see... do

let titles = []
let cats = [{name: "abc", id: 1},{name: "def", id: 2},{name: "gh", id: 3}]
 for( var p = 0 ;p< cats.length ; p++){
    titles.push(cats[p].id)
 }

console.log(titles)

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

1 Comment

added snippet .
0

If you simply want to extract the ids, and props and/or names may be empty or null, you can do it using map:

const titles = (props && props.names || []).map(val => val.id);

Here props && props.names || [] will be equal to [] if props or props.names evaluates to falsy. That way, you can still apply map to it, which will return an empty array in this case.

function demo(props) {
  const titles = (props && props.names || []).map(val => val.id);
  console.log(titles);
}

demo({ names: [{name: 'one', id: 1}, {name: 'two', id: 2}, {name: 'three', id: 3}] });
demo({ names: [] });
demo({});
demo(null);

See the MDN doc about the map operator.

1 Comment

How would this help if props is empty?

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.