0

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

3 Answers 3

1

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

Comments

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.