[英]Elegant array transformation in Javascript
什么是一种优雅的方式 - 纯粹的功能,理想情况下 - 转换(减少?)这个数组:
var in = [
{ a: 1, b: 'x', c: 'foo' },
{ a: 1, b: 'y', c: 'goo' },
{ a: 2, b: 'x', c: 'hoo' },
{ a: 2, b: 'y', c: 'joo' }
]
进入:
var out = [
{ a: 1, x: 'foo', y: 'goo' },
{ a: 2, x: 'hoo', y: 'joo' }
]
的逻辑是,所有内容应基于它们被接合a
属性,并且所有b
和c
性质分别表示键/值对应合并成基于它们共享的单个对象a
值。
您可以使用哈希对象,并使用reduce
来包装哈希:
const arr = [ { a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' } ]; let result = Object.values( // the result is the values of the hash object arr.reduce((hash, o) => { // hash is a hash object that make it easier to group the result hash[oa] = hash[oa] || {a: oa}; // if there is no object in the hash that have the value of the key a equal to oa, then create a new one hash[oa][ob] = oc; // set the value of the key stored in ob to oc return hash; }, {}) ); console.log(result);
你可以使用带有Map
的闭包
var input = [{ a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' }], output = input.reduce((map => (r, o) => (!map.has(oa) && map.set(oa, r[r.push({ a: oa }) - 1]), map.get(oa)[ob] = oc, r))(new Map), []); console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以使用forEach
和Object.assign
按a
进行分组,然后map
以返回对象值。
var data = [ { a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' } ] var r = {} data.forEach(e => r[ea] = Object.assign((r[ea] || {}), {a: ea, [eb]: ec})) r = Object.keys(r).map(e => r[e]) console.log(r)
不确定方法是优雅还是功能,但使用for..of
循环返回预期结果, Array.prototype.some()
和Object.assign()
function props(array, key, prop1, prop2) { let arr = []; for (let obj of array) { let o = {}; for (let {[key]:_key, [prop1]:_prop1, [prop2]:_prop2} of [obj]) { o[_prop1] = _prop2; o[key] = _key; } if (!arr.some(p => p[key] === o[key])) arr.push(o); for (let prop of arr) { if (prop[key] == o[key]) { prop = Object.assign(prop, o) } } } return arr } var _in = [ { a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' } ]; console.log(props(_in, "a", "b", "c"));
我喜欢提供的答案,但这是我的尝试。 我相信它更具可读性,但它使用Object.assign
和Object.values
const input = [
{ a: 1, b: 'x', c: 'foo' },
{ a: 1, b: 'y', c: 'goo' },
{ a: 2, b: 'x', c: 'hoo' },
{ a: 2, b: 'y', c: 'joo' }
]
const map = input.reduce((acc, obj) => {
const [a, key, value] = Object.values(obj)
const newObj = {a, [key]: value}
if (acc[a]) {
Object.assign(acc[a], newObj)
} else {
acc[a] = newObj
}
return acc
}, {})
console.log(Object.values(map))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.