【问题标题】:How can I wrap the value of json with curly braces?如何用花括号包裹 json 的值?
【发布时间】:2019-07-05 02:50:32
【问题描述】:

假设我有这样的 json(使用 JSON.stringify)

{ 姓名:'比尔',姓氏:'史密斯'}

我想要用这样的花括号包裹的值

{姓名:{值:'比尔'},姓氏:{值:'史密斯'}}

那么有什么想法可以使用 javascript 或 lodash 来做这样的事情吗?

【问题讨论】:

  • 我能知道原因吗?

标签: javascript json typescript lodash


【解决方案1】:

我会在输入上使用Object.entries,映射到嵌套对象,然后调用Object.fromEntries 再次将其转换回来:

const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.fromEntries(
  Object.entries(input).map(
    ([key, value]) => ([key, { value }])
  )
);
console.log(newObj);

Object.fromEntries 是一种非常新的方法,因此对于旧版浏览器,要么包含一个 polyfill,要么使用类似 .reduce 的东西:

const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.entries(input).reduce(
  (a, [key, value]) => {
    a[key] = { value };
    return a;
  },
  {}
);
console.log(newObj);

【讨论】:

    【解决方案2】:

    您可以使用for...in 循环遍历对象的键并像这样更新它:

    const input = { name: 'Bill', lastname: 'Smith'};
    
    for (const key in input) {
      input[key] = { value: input[key] }
    }
    
    console.log(input)

    如果你不想改变输入并且想创建一个新对象,那么创建另一个对象并更新它:

    const input = { name: 'Bill', lastname: 'Smith'},
          output = {}
    
    for (const key in input) {
      output[key] = { value: input[key] }
    }
    
    console.log(output)

    【讨论】:

      【解决方案3】:

      您可以使用 lodash 的 _.mapValues() 来返回具有转换值的新对象:

      const object = { name: 'Bill', lastname: 'Smith'};
      
      const result = _.mapValues(object, value => ({ value }));
      
      console.log(result);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 2015-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多