JavaScript数据转换

时间:2019-03-21 17:10:36

标签: javascript lodash

输入:

     {
    "8": [{
        "a": true,
        "b": {
            "xyz": 1
        }
    }, {
        "a": false,
        "b": {
            "xyz": 2
        }
    }],
    "13": [{
        "b": {
            "xyz": 4
        }
    }]
 }

输出:

    {
    "8": [{
        "b": {
            "xyz": 2
        }
    }]
 }

如何使用javascript和lodash库删除每个键的第一个元素并返回同一对象的几个键?

3 个答案:

答案 0 :(得分:2)

在没有loadash的情况下使用Array#shiftArray#foreach

  1. 首先使用Object.keys将obj转换为数组
  2. 然后循环值。并使用Array#shift
  3. 删除数组的第一个索引
  4. 然后将数组长度为0的应用条件从主对象中删除键值对

var obj = { "8": [{ "a": true, "b": { "xyz": 1 } }, { "a": false, "b": { "xyz": 2 } }], "13": [{ "b": { "xyz": 4 } }] };
Object.keys(obj).forEach(a => {
  obj[a].shift()
  obj[a] = obj[a];
  if(obj[a].length == 0)
   delete obj[a];
});
console.log(obj)

答案 1 :(得分:1)

您可以这样使用reduce返回的条目Object.entries()

let obj={"8":[{"a":!0,"b":{"xyz":1}},{"a":!1,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}

let output = Object.entries(obj).reduce((acc, [key, value]) => {
  if(value.length > 1)
    acc[key] = value.slice(1)
  
  return acc;
}, {})

console.log(output)

如果要变异原始对象,请使用for...in遍历对象,并使用shiftdelete,如下所示:

let obj={"8":[{"a":!0,"b":{"xyz":1}},{"a":!1,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}

for (let key in obj) {
  obj[key].shift()
  if (obj[key].length === 0)
    delete obj[key]
}

console.log(obj)

答案 2 :(得分:0)

使用lodash_.flow()_.partialRight()创建一个函数,该函数将值映射到每个数组的尾部(除第一项之外的所有项),然后使用{{1 }}删除空键:

_.omitBy()
const { flow, partialRight: pr, mapValues, tail, omitBy, isEmpty } = _

const fn = flow(
  pr(mapValues, tail),
  pr(omitBy, isEmpty)
)

const data = {"8":[{"a":true,"b":{"xyz":1}},{"a":false,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}

const result = fn(data)

console.log(result)

以及更短的lodash/fp版本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
const { flow, mapValues, tail, omitBy, isEmpty } = _

const fn = flow(
  mapValues(tail),
  omitBy(isEmpty)
)

const data = {"8":[{"a":true,"b":{"xyz":1}},{"a":false,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}

const result = fn(data)

console.log(result)