zishu's blog

zishu's blog

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

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

A method required in the business, where an array is returned by the interface, which contains 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 properties named "name" from it 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.