zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Extract and merge the values of the same-named properties from multiple objects in the array into a new array

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"
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.