简体   繁体   English

使用 .map() 遍历 Object 值数组并重新分配给新键

[英]Using .map() to iterate over an array of Object values and reassign to new keys

I am trying to transform the data below from:我正在尝试将以下数据转换为:

{
      title: 'The Promise',
      blurb: 'Lorem Ipsum',
      cover_image: 'Lorem Ipsum',
      pub_year: 2002,
      genre: 'Foobar'
    }

To:至:

[
 {
   col1: 'The Promise',
   col2: 'Lorem Ipsum',
   col3: 'Lorem Ipsum',
   col4: 2002
   col5: 'Foobar'
 },
]

I have been puzzling away at this for quite a while and can only get it looking like this, which is just seperate objects rather than a single object as part of an array of objects (there are other book objects in the returned JSON from my db the function needs to churn through)我对此困惑了很长时间,只能让它看起来像这样,这只是单独的对象,而不是作为对象数组的一部分的单个对象(从我的数据库返回的 JSON 中还有其他书籍对象该功能需要通过)

{col1: 1} //this is an id
{col2: 'The Promise'}
{col3: 'Lorem ipsum'}
{col4: Lorem Ipsum}
{col5: '2002'}
{col6: Foobar}

Here is the code I have been working on:这是我一直在处理的代码:

 const data = React.useMemo(
    () =>
      props.tableData.map((object, i) => {
        Object.values(object).map((value, i) => {
          let col = `col${i + 1}`
          const obj = { [col]: value }
        })
      }),
    [props.tableData]
  )

When mapping the values, instead of constructing an object containing a single property, return an entry pair (an array where the first value is the property, and the second value is the associated value) so that you can turn the array of entries into an object with Object.fromEntries .映射值时,不是构造一个包含单个属性的对象,而是返回一个条目对(一个数组,其中第一个值是属性,第二个值是关联值),以便您可以将条目数组转换为带有Object.fromEntries的对象。

const data = React.useMemo(
    () =>
        props.tableData.map((object) => (
            Object.fromEntries(
                Object.values(object).map((value, i) => [`col${i + 1}`, value])
            )
        )),
    [props.tableData]
);

This depends on the properties in your input objects being ordered.这取决于要排序的输入对象中的属性。 While this is usually dependable, it's not a good thing to rely on, and won't work if any of the properties become numeric (eg 1 or 5 ).虽然这通常是可靠的,但依赖它并不是一件好事,并且如果任何属性变为数字(例如15 )将不起作用。 Consider if the input object properties could be formatted as an (ordered) array instead.考虑是否可以将输入对象属性格式化为(有序)数组。

It just needed a little tweak.它只需要一点点调整。 Instead of using map , which returns a new array of mapped elements, use a reducer function to create a new singular object.与其使用返回映射元素的新数组的map ,不如使用reducer函数创建一个新的奇异对象。

 const data = { title: 'The Promise', blurb: 'Lorem Ipsum', cover_image: 'Lorem Ipsum', pub_year: 2002, genre: 'Foobar' } function transformIntoColumns(dataToTransform) { return Object.keys(dataToTransform).reduce((transformed, prop, index) => { transformed[`col${index + 1}`] = dataToTransform[prop]; return transformed; }, {}); } console.log(transformIntoColumns(data));

Another way of achieving this is to use a simple forEach , and the advantage is that you would have one iteration instead of two.实现此目的的另一种方法是使用简单的forEach ,其优点是您将进行一次迭代而不是两次。 Like this:像这样:

 const data = { title: "The Promise", blurb: "Lorem Ipsum", cover_image: "Lorem Ipsum", pub_year: 2002, genre: "Foobar" }; const formatData = () => { let result = {}; Object.values(data).forEach((v, i) => { result["column" + Number(i + 1)] = v; }); return result; }; console.log(formatData());

To adapt to your use case:为了适应您的用例:

const data = React.useMemo(() => {
  let result = {};
  Object.values(props.tableData).forEach((v, i) => {
    result["column" + Number(i + 1)] = v;
  });
  return result;
}, [props.tableData]);

You could have a mapping object that maps the old keys to the new keys - that way it doesn't matter if they're not in order when you iterate over them.您可以有一个映射对象,将旧键映射到新键 - 这样,当您迭代它们时它们是否不按顺序无关紧要。

 const mapping={title:"col1",blurb:"col2",cover_image:"col3",pub_year:"col4",genre:"col5"}; const tableData=[{title:"The Promise",blurb:"Lorem Ipsum",cover_image:"Lorem Ipsum",pub_year:2002,genre:"Foobar"}]; const result = tableData.map(obj => { const out = {}; for (const prop in obj) { out[mapping[prop]] = obj[prop]; } return out; }); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM