You can use Array.prototype.map for that:
var arr = [
{"text":"demo1"},
{"text":"demo2"}
];
var texts = arr.map(function(el) {
return el.text;
});
console.log(texts);
And with ES6, you can use arrow functions:
var texts = arr.map((el) => el.text);
Answer from str on Stack OverflowYou can use Array.prototype.map for that:
var arr = [
{"text":"demo1"},
{"text":"demo2"}
];
var texts = arr.map(function(el) {
return el.text;
});
console.log(texts);
And with ES6, you can use arrow functions:
var texts = arr.map((el) => el.text);
You can use map() for this:
var myArray = [ {"text": "demo1"}, {"text": "demo2"} ];
var newArray = myArray.map( el => el.text); // [ "demo1", "demo2"]
Basically map() performs an operation on every element of an array returning a new array.
It's hard to do this with reduce() when you have such a small array, but still possible:
var myArray = [ {"text": "demo1"}, {"text": "demo2"} ];
var newArray = myArray.reduce( (a,b) => [a.text, b.text]) // [ "demo1", "demo2" ]
In this example a is the first item and b is the second item.
The simplest way is as follows
getStates().map(x=>x.StateName).join(",")
Example is given below
function State(id,val,StateName) {
this.id = id;
this.val = val;
this.StateName = StateName;
}
function getStates() {
return [
new State(1, 1, 'Arizona'),
new State(2, 1, 'Alaska'),
new State(3, 1, 'Florida'),
new State(4, 1, 'Hawaii'),
new State(5, 2, 'Gujarat'),
new State(6, 2, 'Goa'),
new State(7, 2, 'Punjab'),
new State(8, 3, 'Queensland'),
new State(9, 3, 'South Australia'),
new State(10, 3, 'Tasmania'),
new State(11, 4, 'Penang')
];
}
//Simplest Way is as follows
console.log(getStates().map(x=>x.StateName).join(","))
Well the most simplest way to convert an array to comma-separated string is
var commaSeperatedString = arrayName.toString();
Basically you could just use:
var stringArray = [{id: 'svg', name: 'JASSI'}];
var objectArr = [];
stringArray.map(function(item) {
objectArr.push(item.name);
});
console.log(objectArr);
It's close but you're setting indexes on an array which will be an object. Instead, simply append the field name.
$scope.stringArrayToObjectArray = function(stringArray, fieldName) {
var objectArr = [];
angular.forEach(stringArray, function(singleString) {
objectArr.push(singleString[fieldName]);
});
return objectArr;
};
Check out this jsfiddle. You'll see both Array.prototype.reduce and Array.prototype.map used, both with the same results.
This is classic reduce:
var people = person.reduce(function(agg, p) {
return agg.concat([p.name + p.age + p.address]);
}, []);
The above uses Array.prototype.reduce.
In other words, when you want all the properties of an object or array "reduced" into something, then the most semantic go-to option is probably Array.prototype.reduce in this case.
However, Array.prototype.map can also do the job quite cleanly:
var people = person.map(function(p) {
return p.name + p.age + p.address;
});
This is an argument, now, between readability/complexity vs. semantics.
To limit incidental complexity (in the form of readability), I might go for the map function, even though you could argue this is technically a paradigmatic reduction.

Try this, this method suitable for different object names, it will work good.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc@xyz.co'}
];
var result = person.map(function(p){ return Object.keys(p).map(function(k){return p[k]}).join("");})
call a method that does the job. Something like this:
getSkills(element: any): string {
let skills = "";
element.skills.forEach(skill => {
skills += skill.skill_name + ", ";
}
return skills;
}
<!-- skills Column-->
<ng-container matColumnDef="skills">
<th mat-header-cell *matHeaderCellDef> Skills </th>
<td mat-cell *matCellDef="let element"> {{getSkills(element)}} </td>
</ng-container>
You has two options
1.-Iterate over skills
<td mat-cell *matCellDef="let element">
<span *ngFor="skill of element.skills;let last=last">
{{skill.skill_name}}{{!last?' - ':''}}</span>
</td>
2.-add a new property, e.g. skillsTxt with the name of skills
When you has the data
this.data.forEach(x=>{
x.skillsTxt=x.skills.map(s=>s.skill_name).Join(" - ");
})
And use in td
<td mat-cell *matCellDef="let element">
{{element.skillsTxt}}
</td>
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
If your array of objects is items, you can do:
var items = [{
id: 1,
name: 'john'
}, {
id: 2,
name: 'jane'
}, {
id: 2000,
name: 'zack'
}];
var names = items.map(function(item) {
return item['name'];
});
console.log(names);
console.log(items);
Documentation: map()
Use the map() function native on JavaScript arrays:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});
You could just run a simple conversion on it using the ConvertAll method in the Array class and a lambda on the object itself.
object[] inputArray = new object[10];
string[] resultArray = Array.ConvertAll(inputArray, x => x.ToString());
If you have a method to convert an object to a string (or int) with null check, then you can use the Array.ConvertAll<TInput, TOutput> Method to convert an object[] to a string[] (or int[]):
object[] input = ...;
string[] result = Array.ConvertAll<object, string>(input, ConvertObjectToString);
string ConvertObjectToString(object obj)
{
return obj?.ToString() ?? string.Empty;
}
If you want to skip items in the object[] array when converting to a string[], a more convenient approach might be using the extension methods of the Enumerable Class:
object[] input = ...;
string[] result = input.Where(x => x != null)
.Select(x => x.ToString())
.ToArray();
You can use the KeyValuePipe and you don't have to change anything in the object
export interface Isummary {
toto: string[];
foo: string[];
}
@Component({
selector: "example",
template: `
<div *ngFor="let item of object | keyvalue">
<span>key: {{ item.key }}</span>
<span>Values</span>
<span *ngFor="let value of item.value">{{ value }}</span>
</div>
`,
})
export class ExampleComponent {
object: Isummary = {
toto: ["titi", "tata"],
foo: ["foobar", "footix"],
};
}
or you can use Object.entries
@Component({
selector: "example",
template: `<div *ngFor="let item of object">
<span>key: {{ item[0] }}</span>
<span>Values</span>
<span *ngFor="let value of item[1]">{{ value }}</span>
</div>`,
})
export class ExampleComponent {
object = Object.entries({
toto: ["titi", "tata"],
foo: ["foobar", "footix"],
});
}
The answer of @Chris is the Angular way of doing it. Here is another approach from the js only side.
Assume we have:
{
"toto": [
"titi",
"tata"
],
"foo": [
"foobar",
"footix"
]
}
You can use this, to transform it into an array:
const toArray = (data) => {
return Object.keys(data).map(key => data[key]);
}
In the end it should look like this:
[
[
"titi",
"tata"
],
[
"foobar",
"footix"
]
]
this.myHero = this.heroes[0].name; // display the name
Or if you want to keep your selected hero as an object then display the name in the template.
app.component.html
{{myHero.name}}
As for the array you need to loop over it and display something interesting on the object from the array itself.
<div *ngFor="#hero of heroes">
{{hero.name}}
</div>
From your comment, here is your fixed code that displays the name of the myHero instance and from loop over the heros array.
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul>
You are assigning Hero class object(s) to string variable which is not compatible. So, rather than changing it to string, declare it with Hero class type. So,
myHero: string;
change it to
myHero: Hero;
And in template use it with property like,
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul>
<li *ngFor="let hero of heroes"> {{ hero.name}} </li>
</ul>
or if You like to more functional code:
var arr = [];
angular.forEach(obj, function(value, key){
arr.push(value);
});
If you are using underscore.js,
_.values(formData)
// will get ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
See: here
Alternatively:
var res = [];
for (var x in formData){
formData.hasOwnProperty(x) && res.push(formData[x])
}
console.log(res);
In any event, the array elements might not be in the order that you want.