[英]How to map two arrays of objects, concatenate them, and add an index efficiently
I have two different arrays of objects that need to be mapped individually to key:value pairs defined by me. 我有两个不同的对象数组,需要分别映射到我定义的key:value对。 When mapping, each of the objects should be assigned a sequential index. 映射时,应为每个对象分配一个顺序索引。 Then, I need to take each of the mapped arrays and concatenate them. 然后,我需要获取每个映射的数组并将其连接起来。
This is what I've tried so far. 到目前为止,这是我尝试过的。 It works, but I think there might be a more efficient or clean way to do it: 它可以工作,但是我认为可能有更有效或更干净的方法:
const mapPosts = () => {
let index = 0
const mappedPostsA = postsA.map(post => {
index++
return {
id: index,
provider: 'Wordpress',
post_id: postA.id,
title: postA.title,
body: postA.body_html
}
})
const mappedPostsB = postsB.map(post => {
index++
return {
id: index,
provider: 'Blogspot',
post_id: postB.id,
title: postB.title,
body: postB.description
}
})
const mappedPosts = [...mappedPostsA, ...mappedPostsB])
}
You could just offset the index by the length of postsA
, as you know postsB
will always be right after it. 您可以将索引仅按postsA
的长度postsA
,因为您知道postsB
总是postsB
其后。
const mapPosts = (postsA, postsB) => {
return [
...postsA.map((post, index) => ({
id: index,
provider: 'Wordpress',
post_id: post.id,
title: post.title,
body: post.body_html
}))
...postsB.map((product, index) => ({
id: index + postsA.length,
provider: 'Blogspot',
post_id: product.id,
title: product.title,
body: product.description
}))
];
};
I used the spread syntax since you used it in your original question, you could use something like mappedA.concat(mappedB)
instead, but this is mostly a matter of preference. 因为您在原始问题中使用了扩展语法,所以我使用了扩展语法,可以改用诸如mappedA.concat(mappedB)
类的东西,但这主要是优先考虑的问题。
If you're concerned about efficiency, and if you have a lot of objects, you might want to consider using a Map instead of a plain object. 如果您担心效率,并且有很多对象,则可能要考虑使用Map而不是普通对象。 Maps are specifically tailored to efficiently handle key-value pairs. 地图是专门为有效处理键值对而定制的。 You might get a slight performance boost, or at least slightly more readable code. 您可能会略微提高性能,或者至少获得稍微易读的代码。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map
To remove code duplication, I'd probably do 为了消除代码重复,我可能会做
const mappedPostsA = postsA.map(post => ({post, provider: 'Wordpress', body: post.body_html}));
const mappedPostsB = postsB.map(post => ({post, provider: 'Blogspot', body: post.description}));
const mappedPosts = [].concat(mappedPostsA, mappedPostsB).map(({post, provider, body}, index) => ({
id: index,
provider,
post_id: post.id,
title: post.title,
body,
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.