【问题标题】:How to remove square braces [] from an object in JavaScript [duplicate]如何从JavaScript中的对象中删除方括号[] [重复]
【发布时间】:2020-10-22 07:15:32
【问题描述】:

考虑以下对象

var obj1=[
    {
      'Charles Byers': 'Industrials',
      'David Smith': 'Industrials',
      'Joe Evans': 'Industrials',
      'Larry Young': 'Industrials',
      'Martin Hammond': 'Industrials',
      'William Green': 'Industrials'
    }
  ]

我需要删除开始和结束的方括号 [] 而不将其转换为字符串 喜欢,

var obj1=
          {'Charles Byers': 'Industrials',
          'David Smith': 'Industrials',
          'Joe Evans': 'Industrials',
          'Larry Young': 'Industrials',
          'Martin Hammond': 'Industrials',
          'William Green': 'Industrials'}
       

我怎样才能做到这一点?

注意:对象的大小和内容可能会改变。

【问题讨论】:

    标签: javascript json object split


    【解决方案1】:

    您可以从单个键/值对获取条目并映射新对象。

    const
        object = { 'Charles Byers': 'Industrials', 'David Smith': 'Industrials', 'Joe Evans': 'Industrials', 'Larry Young': 'Industrials', 'Martin Hammond': 'Industrials', 'William Green': 'Industrials' },
        result = Object
            .entries(object)
            .map(keyValue => Object.fromEntries([keyValue]));
    
    console.log(result);

    【讨论】:

    • 键名和值名可能会改变。那个时候我能做什么? @Nina Scholz
    • 你有例子吗?发生了什么变化?请在问题中添加任何其他信息。
    • 这是格式。对象的内容可能会改变。我需要把它们分开。 @Nina Scholz
    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 2018-08-15
    • 2015-09-10
    • 2016-04-29
    • 2013-04-11
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多