In business requirements, there is a method where an array is returned by an interface, containing a large number of objects with the same property names, which is quite common. However, it is necessary to extract all the values of the property named 'name' from them and merge them into an array.
const num = [
{
id: 1,
name: 'abc',
},
{
id: 2,
name: 'xyz',
}
]
function getFields(arrnum, field) {
const resnum = [];
for (let i = 0; i < arrnum.length; ++i)
resnum.push(arrnum[i][field]);
return resnum;
}
const result = getFields(num, "name");
console.log(result); // ['abc', 'xyz']
console.log(result.join(' ')); // "abc xyz"