0

I have an array that looks like this

   const array: any[] = []
   array.push({ 'Comments': this.comment, 'Name': this.name, 'Description' : this.description })

I pass that array back to a parent component. How can I grab the value that is in Comments?

3
  • What have you tried, how did it not work? Or do you just not know the basic access operations? Commented Sep 30, 2017 at 15:31
  • 3
    This has nothing to do with TypeScript nor AngularJS. Commented Sep 30, 2017 at 15:31
  • Suggest changing the title to remove 'typescript' Commented Jan 11, 2023 at 5:04

4 Answers 4

5

You can use forEach loop :

const commentArray = [];
array.forEach(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//You can store all comments in another array and use it...
console.log("This is comment array...", commentArray);

Or use map but it will work in new browsers possibly ones following ES6:

const commentArray = array.map(function(object) {
    return object.Comments;
});
console.log("This is comment array... ", commentArray);
Sign up to request clarification or add additional context in comments.

3 Comments

I got it I needed to a .join to remove the comma that was being automatically added to string.
Just out of curiosity which one of the two options did you try :)
The second one because it is shorter.
1

As long as TGW's answer is "correct" and works, I think you should be aware of and use for...of (and for...in) construction, it's superior over Array.forEach (faster, you can use continue and break keywords, better readability) and more often you want to iterate over your array and do things with it, than just get one property (which Array.map is perfect for in this case :) )

Comments

0

You may try for this:

We can also use filter here.

let commentArray:any[];
array.filter(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//Store here and use this.
console.log("This is comment array...", commentArray);

Comments

-1

You can use Underscore JS for short and better performance like below:

    let ids: Array<number> = _.map(this.mylist, (listObj) => {
        return listObj.Id;
    });

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.