javascript 如何展平对象的嵌套数组并复制父对象[已关闭]

w8ntj3qf  于 2023-01-08  发布在  Java
关注(0)|答案(4)|浏览(149)

13小时前关门了。
Improve this question
我有一个对象数组,它有一个属性("attributes")作为对象数组。

var products = [
    {
        "productId": "1",
        "attributes": [
            {
                "variant":"red",
                "price": "134.00"
            }
        ]
    },
    {
        "productId": "2",
        "attributes": [
            {
                "variant": "green",
                "value": "3400.00"
            },
            {
                "variant": "pink",
                "price": "342.00"
            }
        ]
    }
]

我想对象的嵌套数组被展平并复制到父对象上,但父对象需要为每个嵌套对象复制。(不确定我是否解释正确)。
转换后的对象数组应为:

var transformedProducts = [
    {
        "productId": "1",
        "variant":"red",
        "price": "134.00"
    },
    {
        "productId": "2",
        "variant": "green",
        "value": "3400.00"
    },
    {
        "productId": "2",
        "variant": "pink",
        "price": "342.00"
    }
]

我可以Map外层数组,然后再Map内层数组,在最内层的Map中,构造一个新对象。
对此是否有更好或更实用的方法?

mqkwyuun

mqkwyuun1#

可以使用Array.flatMap()迭代对象,然后使用Array.map()迭代attributes,并与对象的其余部分组合。Array.flatMap()还可以将数组的数组扁平化为单个数组。

const fn = arr => arr.flatMap(({ attributes, ...rest }) => 
  attributes.map(o => ({
    ...rest,
    ...o
  }))
)

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)

在Ramda中,你可以使用R.chain迭代和扁平化数组。要获得一个属性数组和它们的父属性组合,你可以使用R.ap作为两个函数的组合子:
1.提取attributes数组,然后将其应用于第二个函数。
1.获取对象的其余部分(不包括属性),并创建将其合并到迭代对象的Map函数。
x一个一个一个一个x一个一个二个x

ars1skjm

ars1skjm2#

可以按如下方式使用Array#mapArray#flat

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({productId,attributes}) => 
    attributes.map(({variant,price}) => ({productId,variant,price}))
)
.flat();

console.log( output );

或者,如果存在其他属性,则仅命名为attributes

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({attributes,...rest}) => 
    attributes.map(attribute => ({...rest,...attribute}))
)
.flat();

console.log( output );
qgelzfjb

qgelzfjb3#

这段代码应该适合你:

const transformedProducts = [];

products.forEach((product) => {
    product.attributes.forEach((attribute) => {
        transformedProducts.push({
            productId: product.productId,
            ...attribute,
        });
    });
});
xwbd5t1u

xwbd5t1u4#

在我的例子中,我的数组有对象,在对象中有子数组。我想要一个包含所有子对象的数组
所以我用这个函数把所有对象放到一个数组里

let array = [
      {
        id: 1,
        title: 't1',
        sort_order: 200,
        childs: [
          {
            id: 2,
            title: 't2',
            sort_order: 200,
            childs: [],
          },
          {
            id: 3,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 4,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 5,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 6,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
      {
        id: 7,
        title: 'راهنما',
        sort_order: 'mytitle',
        childs: [
          {
            id: 8,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 9,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 10,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
    ];

这是我代码

let flattenArray = [];

function flatten(a) {
  flattenArray.push(a);
  if (a.childs?.length) a.childs.map(flatten);
}

array?.map((el) => {
  flattenArray.push(el);
  if (el.childs?.length) el.childs.map(flatten);
});

console.log(flattenArray);

结果:

[
    {
        "id": 1,
        "title": "t1",
        "sort_order": 200,
        "childs": [
            {
                "id": 2,
                "title": "t2",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 3,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 4,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 5,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 6,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 2,
        "title": "t2",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 3,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 4,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 5,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 6,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 7,
        "title": "راهنما",
        "sort_order": "mytitle",
        "childs": [
            {
                "id": 8,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 9,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 10,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 8,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 9,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 10,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    }
]

相关问题