通过公用键/索引合并数组项和对象值

时间:2020-07-03 21:11:38

标签: javascript

我有一个这样的数组数组:

let a = [ 
   ['A', 'B'], // 1 in the object
   ['C'], // 2 in the object
];

我有一个这样的对象:

let b = {
    5:{
         1: "i was send to earth. i was send to her.",
         2: "to mars",
         3: { reference: "to moon.", expectSt: "to mars. i love it." },
    },
};

如您所见,对象中有两种模式。像1和2这样的模式以及像3这样的模式。

我只想在let a内的第一个数组中添加1的句子,并在let a内的第二数组中添加2的句子,依此类推...

如果模式是3,那么我只想添加expectSt的句子而忽略reference

结果应为:

let a = [ 
       ['A', 'B', 'i was send to earth', 'i was send to her'], // 1 in the object
       ['C', 'to mars'], // 2 in the object
       ['to mars', 'i love it'], // there is a 3 i the object so we added this
];

我已经尝试了很多,但是我认为我需要帮助解决这个问题。

2 个答案:

答案 0 :(得分:1)

像这样简单的事情对您有用吗?

let a = [['A','B'],['C'],],
    b = {5:{1:"i was send to earth. i was send to her.",2:"to mars",3:{reference:"to moon.",expectSt:"to mars. i love it."},},}
    
Object
  .values(b[5])
  .forEach((value,key) => 
    a[key] = [
      ...(a[key]||[]), 
      ...(value.expectSt || value)
        .toLowerCase()
        .replace(/\.$/,'')
        .split('. ')
    ]
  )   
    
console.log(a)
.as-console-wrapper{min-height:100%;}

答案 1 :(得分:0)

let a = [ 
  ['A', 'B'], // 1 in the object
  ['C'], // 2 in the object
];

let b = {
  5:{
       1: "i was send to earth. i was send to her.",
       2: "to mars",
       3: { reference: "to moon.", expectSt: "to mars. i love it." },
  },
};

Object.values(b).forEach(element => {
  Object.keys(element).forEach(e => {
    console.log(element[e]);
    if(e === '1') a[0].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
    else if(e === '2') a[1].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
    else if(e === '3') {
      if(a.length < 3) a.push([]);
      a[2].push(...element[e].expectSt.split('.').filter(a => a !== '').map(a => a.trim()))
    } 
  })
});

console.log(a);