Sara Ree
Sara Ree

Reputation: 3543

Merge array items and object values by common key/index

I have an array of arrays like this:

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

and I have an object of objects like this:

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." },
    },
};

As you see there are two patterns in the object. the pattern like 1 and 2 and the pattern like 3.

I just want to add sentences in 1 to the first array inside let a and sentences in 2 to the second array inside let a and so on...

and if the pattern was like 3 then I just want to add sentences of expectSt and ignore reference

The result should be this:

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
];

I have tried a lot but I think I need a hand to solve this.

Upvotes: 0

Views: 57

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Would something as simple as that work for you?

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%;}

Upvotes: 1

razouq
razouq

Reputation: 101

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);

Upvotes: 0

Related Questions