【问题标题】:Javascript: Convert list of values to set of ObjectsJavascript:将值列表转换为对象集
【发布时间】:2020-09-23 05:41:51
【问题描述】:

我正在从服务器获取数据..

从服务器返回的数据是..

{
 Increase: true,
Decrease: false,
Like:true,
Unlike: true,
Others: false,
Limits:true
}

以下是我在 Ngrx 服务调度后得到的结果

console.log('this.data=' +data);

this.data= [object Object]

现在做完 console.log('Object.keys(data)='+ Object.keys(data));

Object.keys(data)= Increase,Decrease,Like,Unlike,Others,Limits

如何在 console.log 之后获得如下相同的数据集

  [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

这样在 JSON.stringify 之后.. 我可以得到相同的数据,如下所示

[{"description":"Increase"},{"description":"Decrease"},{"description":"Like"},{"description":"Unlike"},{"description":"Others"},{"description":"Limits"},]

【问题讨论】:

  • 我建议您开始使用逗号分隔console.log 中的元素:console.log('this.data=', data); 看到实际对象而不是[object Object] 更有用。
  • Object.entries() + Array.prototype.map()

标签: javascript jquery arrays json typescript


【解决方案1】:

您可以使用Object.keys() 然后.map() 结果数组,这是一个有效的sn-p:

const obj = {
  Increase: true,
  Decrease: false,
  Like: true,
  Unlike: true,
  Others: false,
  Limits: true,
};

//const result = Object.keys(obj).map((key) => ({ description: key }));

const result = Object.keys(obj).map((key) => ({ [key]: obj[key]}));

console.log(JSON.stringify(result));

【讨论】:

    【解决方案2】:

    你可以拿entries然后映射一下:

    var obj={ Increase: true, Decrease: false, Like:true, Unlike: true, Others: false, Limits:true};
    
    var result = Object.entries(obj).map(([k,v])=>({[k]:v}));
    
    var result2 = Object.entries(obj).map(([k])=>({'Description':k}));
    
    console.log(result);
    console.log(result2);

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 2015-04-14
      • 2020-07-14
      • 2019-10-03
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多