Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - 根据对象数组中的键创建对象(Create an object based on the keys in array of objects)

I am having an array of objects and I want to create another object based on their keys.

(我有一个对象数组,我想根据它们的键创建另一个对象。)

For example I am having an array as

(例如我有一个数组)

var arr = [{1: 36011, 2: 18320, 3: 36011, 4: 10570},
            {1: 19754, 2: 6722, 3: 19754, 4: 6699},
            {1: 15711, 2: 10039, 3: 15711, 4: 4172}]

and I want my result array as

(我希望我的结果数组为)

var result = {1:[36011,19754,15711], 2:[18320,6722,10039],..}

I was suggested to use lodash, I am new to this so I've tried using reduce

(建议我使用lodash,我是新手,所以我尝试使用reduce)

var i = 1, new_arr = {};
_.reduce(arr, function(key, val){
     new_arr[i++] = temp1.key 
return new_arr;
},{})

I am getting the values as undefined .

(我正在获取未定义的值。)

What is the mistake, Can anyone help me with this?

(有什么错误,有人可以帮我吗?)

  ask by SPL translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might look intimidating at first.

(起初,这可能看起来很吓人。)

Start reducing the dataset from an empty object.

(从空对象开始减少数据集。)

Then reduce each row starting with result of outer reduce and build on the result so far.

(然后从外部减少的结果开始减少每一行,并以迄今为止的结果为基础。)

 const addToBucket = (bucket = {}, k, v, prev = bucket[k] || []) => ({ ...bucket, [k]: [...prev, v], }) const toBucket = list => list.reduce( (bucket, row) => Object.entries(row).reduce((b, [k, v]) => addToBucket(b, k, v), bucket), {}, ) const data = [ { 1: 36011, 2: 18320, 3: 36011, 4: 10570 }, { 1: 19754, 2: 6722, 3: 19754, 4: 6699 }, { 1: 15711, 2: 10039, 3: 15711, 4: 4172 }, ] console.log(toBucket(data)) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...