将对象转换为数组对象,但按键名字符数进行缩减

问题描述 投票:1回答:1

我有一个对象。

{
mainTitle: "xx",
press1: {text: "xx", linkUrl: "xx", linkText: "xx"}
press1imgs: [{…}, {…}]
press2: {text: "xx", linkUrl: "xx", linkText: "xx"}
press2imgs: [{…}, {…}]
press3: {text: "xx", linkUrl: "xx", linkText: "xx"}
press3imgs: [{…}, {…}]
press4: {text: "xx", linkUrl: "xx", linkText: "xx"}
press4imgs: [{…}, {…}]
press5: {text: "xx", linkUrl: "xx", linkText: "xx"}
press5imgs: [{…}, {…}]
press6: {text: "xx", linkUrl: "xx", linkText: "xx"}
press6imgs: [{…}, {…}]
}

我想把它缩减为一个数组,但把所有... ... press1, press1imgs, press2, press2Imgs 在同一个索引中。如果按后的数字是一样的,就放到同一个索引中,所以总共会有6个索引,要像这样。

[
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
{text: "xx", linkUrl: "xx", linkText: "xx", img: [{…}, {…}]},
]

我可以把这个对象转换成一个数组,然后从这个数组中得到数字。pressx但我又迷失了如何继续下去,减少、过滤、映射?我的尝试。

 const mapped = Object.keys(this.content).map((key) => ({
    key: key,
    value: this.content[key],
  }));

  console.log(mapped);
  mapped.map((item) => {
    console.log(item.key.charAt(5));
    if (item.key.charAt(5)){

    }
  });
javascript angular typescript filter reduce
1个回答
1
投票

因为键是相当动态的,我怀疑数组方法在这里是不是一个好的选择。我会使用一个循环。

const input = this.content;
const results = [];
let i = 1;
while (input.hasOwnProperty('press' + i)) {
  results.push({
    ...input['press' + i],
    img: input['press' + i + 'imgs'],
  });
  i++;
}

Live snippet:

const input = {
mainTitle: "xx",
press1: {text: "xx", linkUrl: "xx", linkText: "xx"},
press1imgs: [{}, {}],
press2: {text: "xx", linkUrl: "xx", linkText: "xx"},
press2imgs: [{}, {}],
press3: {text: "xx", linkUrl: "xx", linkText: "xx"},
press3imgs: [{}, {}],
press4: {text: "xx", linkUrl: "xx", linkText: "xx"},
press4imgs: [{}, {}],
press5: {text: "xx", linkUrl: "xx", linkText: "xx"},
press5imgs: [{}, {}],
press6: {text: "xx", linkUrl: "xx", linkText: "xx"},
press6imgs: [{}, {}]
}

const results = [];
let i = 1;
while (input.hasOwnProperty('press' + i)) {
  results.push({
    ...input['press' + i],
    img: input['press' + i + 'imgs'],
  });
  i++;
}
console.log(results);
© www.soinside.com 2019 - 2024. All rights reserved.