我怎样才能从 js 中的数组对象中只取几个 属性

How can I take only few property from my array objects in js

我试图从数组对象中只获取 2 个属性。

这是我的数组:

 [
0: {_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)}
1: {_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}
]

我正在 尝试只获取标签和 slug 我的期望是:

[
0: {label: 'new 22', slug: 'new-22'}
1: {label: 'new 33', slug: 'new-33'}
]

我试过这样:但它返回的是完整的数组对象

          let tempArray;
          for (let i = 0; i < data.length; i += 2) {
                tempArray = data.slice(data[i], data[i + 2]);
              }
                setAttributeLabel(tempArray);

只需迭代数组并创建一个具有所需属性的新对象并推入临时数组

const data = [{
    _id: '621723ddc1f73de5f7e4dcb9',
    label: 'new 22',
    slug: 'new-22',
    vendor: 'admin'
  },
  {
    _id: '6217272ec1f73de5f7e4dcba',
    label: 'new 33',
    slug: 'new-33',
    vendor: 'admin'
  }
]

let tempArray = [];
for (let i = 0; i < data.length; i++) {
  tempArray.push({
    label: data[i].label,
    slug: data[i].slug

  })
}
console.log(tempArray);

您可以使用 Array.prototype.map 筛选出所需的属性。

const array = [{_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)}, {_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}];

const newArray = array.map(({label, slug}) => ({label, slug}));

console.log(newArray);

您可以使用 Array.map 创建一个新数组。对于映射的每个元素,您创建一个仅包含您需要的属性的新对象:

arr.map(a => { return { label: a.label, slug: a.slug } } );

不要使用循环,而是尝试使用 javascript pre-defined 函数,例如映射。

    array.map(({ label, slug }) => { 
     return {label, slug}
    });

您可以使用 Array.prototype.reduce 循环遍历数据集,return 仅使用您需要的值作为新对象的一部分

let data = [{_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)},{_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}
];

const result = data.reduce((accumulator, current) => {
  return accumulator.concat({label: current.label, slug: current.slug});
}, []);

console.log(result);

使用Array.map()迭代输入数组并从对象中获取所需的属性。

// Input array
const arr = [
{_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)},
{_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}];

// Array.map() to iterate the input array and get the required properties from an object.
const res = arr.map(({label, slug}) => {
    return {label, slug}
});

// Result
console.log(res);