0

Here are the variables:

let linked = {
  related: [
    [0, 'a', 'b'],
    [0, 'c', 'd', 'e', 'f', 'g'],
    [0, "s"],
    [0, 'd'],
    [0, 'g', 'n', 'h']
  ]
}

let hold = [{
    0: 4, // 0 represents [0,'a','b']
    1: 3 // 1 represents [0,'c','d','e','f','g']
  },
  {
    3: 2, // 3 represents [0,'d']
    4: 6 //  4 represents [0,'g','n', 'h'] 
  } 
];

The hold array contains two objects and each object's property represents index of link.related .

The problem is I want to add values of each hold object property to the first element of linked.related.

So the result should be:

let linked = {
  related: [
    [4, 'a', 'b'],
    [3, 'c', 'd', 'e', 'f', 'g'],
    [0, "s"],
    [2, 'd'],
    [6, 'g', 'n', 'h']
  ]
}

So I want to sum values of hold with the first element of linked.related

2
  • please add the ... part. what is meaning of the second property of the objects? Commented Oct 19, 2019 at 19:06
  • Sorry... ok.... Commented Oct 19, 2019 at 19:06

3 Answers 3

2

You can do it in 2 forEach loops

hold.forEach(x => {
  Object.keys(x).forEach (y => {
    linked.related[y][0] += x[y]
  });
});

let linked = {
  related: [

    [0, 'a', 'b'],
    [0, 'c', 'd', 'e', 'f', 'g'],
    [0, "s"],
    [0, 'd'],
    [0, 'g', 'n', 'h']

  ]
}


let hold = [{
    0: 4,
    1: 3
  },
  {
    3: 2,
    4: 6
  } 
];
hold.forEach(x => {
  Object.keys(x).forEach (y => {
    linked.related[y][0] += x[y]
  });
});
console.log(linked.related);

Sign up to request clarification or add additional context in comments.

1 Comment

I think a misunderstanding happend .. I want to sum them not just add them ...
2

You could iterate hold and get the entries for the update.

var linked = { related: [[0, 'a', 'b'], [0, 'c', 'd', 'e', 'f', 'g'], [0, "s"], [0, 'd'], [0, 'g', 'n', 'h']] },
    hold = [{ 0: 4, 1: 3 }, { 3: 2, 4: 6 }];

hold.forEach(o => Object.entries(o).forEach(([i, v]) => linked.related[i][0] += v));

console.log(linked);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

I think a misunderstanding happend .. I want to sum them not just add them ...
2

You can use forEach and Object.entries

let linked = {related: [[0, 'a', 'b'],[0, 'c', 'd', 'e', 'f', 'g'],[0, "s"],[0, 'd'],[0, 'g', 'n', 'h']]}
let hold =[{0: 4, 1:3},{3: 2, 4:6}]

hold.forEach(v => {
  Object.entries(v).forEach(([k, v]) => {
    linked.related[k][0] += v
  })
})

console.log(linked)

2 Comments

I think a misunderstanding happend .. I want to sum them not just add them ...
@SaraRee it's not mentioned anywhere in question, can you update your question accordingly ? and post the desired output as well, if you want to add them changing = to += will solve

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.