【问题标题】:how to format JS object with Lodash如何使用 Lodash 格式化 JS 对象
【发布时间】:2020-06-06 14:27:31
【问题描述】:

const _ = require('lodash');

org_data = [{ item: 'TESTING123', date: '2020-0610T00:00:00.000Z' },{ item: 'TESTING456', date: '2020-0610T00:00:00.000Z' }]

function formating (rows, key='date') {

  return _.chain(rows).keyBy('item').mapValues(key).value()
};

// output
{
 TESTING123: 2020-0610T00:00:00.000Z,
 TESTING456: 2020-0610T00:00:00.000Z,
}

//expected output
{
 'TESTING123' : '2020-0610T00:00:00.000Z',
 'TESTING456': '2020-0610T00:00:00.000Z',
}

实际上数据是通过 django 后端中的 SQL 查询和项目 (models.TextField()) 和日期 (models.DateTimeField()) 获取的 JS对象好像坏了,不知道有什么办法解决这个问题

【问题讨论】:

  • var result = formating(org_data) var str = Object.keys(result).map(function (key) { return "" + key + "=" + result[key]; })
  • 为什么+“=”?结果变成 ['undefined=2020-0610T00:00:00.000Z']
  • 它给出 ["TESTING123=2020-0610T00:00:00.000Z", "TESTING456=2020-0610T00:00:00.000Z"] 未定义
  • 你能检查一下我的预期输出吗?

标签: javascript node.js django underscore.js lodash


【解决方案1】:

var org_data = [
  { item: 'TESTING123', date: '2020-0610T00:00:00.000Z' },
  { item: 'TESTING456', date: '2020-0610T00:00:00.000Z' }
]

function formating (rows, key = 'date') {
  return _.chain(rows)
    .keyBy('item')
    .mapValues(key)
    .value()
}
var t = formating(org_data)

var str = Object.keys(t).map(function (key) {
  return '' + key + '=' + t[key]
})

console.log(t)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 2021-04-24
    • 2023-03-08
    • 2019-10-14
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多