【问题标题】:How to convert array object to single array?如何将数组对象转换为单个数组?
【发布时间】:2022-11-04 23:18:14
【问题描述】:

我现在有对象数组,我需要将它转换为没有键的单个数组。

我需要这样的数组:-

["test","test"]

如果我得到 undefined 而不是其他值,我还需要删除该值。

我的代码:-

const list = [
    {
        "type": "undefined"
    },
    {
        "type": "test"
    },
    {
        "type": "test"
    }
]

var findAndValue = list.map(Object.values);
console.log(findAndValue);

感谢您的努力!

【问题讨论】:

标签: javascript arrays


【解决方案1】:

如果您只想要一个属性的值,只需从 map 操作返回该属性值:

const list = [
  { "type": "undefined" },
  { "type": "test" },
  { "type": "test" }
];
const result = list.map(x => x.type);
console.log(result);

要过滤掉"undefined" 字符串,请使用filter

const list = [
  { "type": "undefined" },
  { "type": "test" },
  { "type": "test" }
];
const result = list.map(x => x.type).filter(x => x !== "undefined");
console.log(result);

【讨论】:

  • 谢谢@David,这工作正常...
【解决方案2】:

2个步骤:

首先将所有值提取到一个列表中

其次,删除您不想要的任何值

const values = list.map(({ type }) => type)
cosnt filteredValues = values.filter(val => val !== undefined)

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多