输入:
{
"8": [{
"a": true,
"b": {
"xyz": 1
}
}, {
"a": false,
"b": {
"xyz": 2
}
}],
"13": [{
"b": {
"xyz": 4
}
}]
}
输出:
{
"8": [{
"b": {
"xyz": 2
}
}]
}
如何使用javascript和lodash库删除每个键的第一个元素并返回同一对象的几个键?
答案 0 :(得分:2)
在没有loadash的情况下使用Array#shift
和Array#foreach
Object.keys
将obj转换为数组Array#shift
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
遍历对象,并使用shift
和delete
,如下所示:
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)