wen tian
wen tian

Reputation: 441

How to add an object array property?

When reading the attribute name, put the user3 of the attribute user2 and the same attribute into an object attribute name equal to a value.

I want to print it out:

[
  {
    name: 'b',
    user1: 'haha',
  },
  {
    name: 'a',
    user2: 'apple',
    user3: 'xiaomi'
  }
]

my code:

var data = [{
    name: 'b',
    user1: 'haha',
  },
  {
    name: 'a',
    user2: 'apple',
  },
  {
    name: 'a',
    user3: 'xiaomi'
  }
]

var arr = []

for (var i = 0; i < data.length; i++) {
  console.log(data[i].name)
}

Upvotes: 0

Views: 60

Answers (3)

Andy
Andy

Reputation: 63524

reduce over the data to create an object with keys set to the name values, then return the Object.values of that object:

var data = [{ name: 'b', user1: 'haha' }, { name: 'a', user2: 'apple' }, { name: 'a', user3: 'xiaomi' }];

function groupByName(arr) {
  return Object.values(data.reduce((acc, c) => {
    const { name, ...rest } = c;
    acc[name] = acc[name] || {};
    acc[name] = { ...acc[name], name, ...rest };
    return acc;
  }, {}));
}

const output = groupByName(data);
console.log(output);

Upvotes: 1

adel
adel

Reputation: 3507

you can use for loop to find same elements and assign one to the other then remove the found element from the array with splice method

var data = [{
    name: 'b',
    user1: 'haha',
  },
  {
    name: 'a',
    user2: 'apple',
  },
  {
    name: 'a',
    user3: 'xiaomi'
  }
]

for (var i=0 ; i<data.length;i++){
  for(var j=i+1;j<data.length;j++){
    if(data[i].name===data[j].name){
      Object.assign(data[i],data[j])
      data.splice(j,1)
    }
  }
}
console.log(data)

Upvotes: 1

Alireza HI
Alireza HI

Reputation: 1933

The below code is first going to make known the same name fields and then will merge them.

var make_unique = function(xs, key) {
  // find same name fields
  let tmp_result =  xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
  // merge the same ones
  return Object.keys(tmp_result).map(item => {
     return tmp_result[item].reduce(function(rv, x) {
        return Object.assign(rv,x)
     }, {});
  })
};

To call it:

make_unique(data,'name')

Upvotes: 1

Related Questions