将对象值与同一数组中的其他对象进行比较

时间:2020-02-05 11:39:56

标签: javascript reactjs

我有这样的数组。

[{first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
 {first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
 {first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}]

我想检查除机构外值是否相同,然后我想生成一个像这样的数组

[{first_name: "john", age: "30", institution:{name: "inst1, inst2, inst3"}}]

7 个答案:

答案 0 :(得分:3)

如果您使用React.js

您可以尝试以下操作:

App.js

// App.js

import React from "react";
import { addItemToUser } from "./utiles";

export default class App extends React.Component {
  state = {
    users: [
      { first_name: "john", age: "30", institution: { id: 1, name: "inst1" } },
      { first_name: "mike", age: "20", institution: { id: 2, name: "inst2" } },
      { first_name: "ali", age: "40", institution: { id: 3, name: "inst3" } }
    ]
  };

  render() {
    const newUser = {
      first_name: "john",
      age: "30",
      institution: { id: 1, name: "inst2" }
    };
    const userList = addItemToUser(this.state.users, newUser);
    console.log(userList);
    return (
      <div className="App">please check your console</div>
    );
  }
}

utiles.js

// utiles.js

export const addItemToUser = (users, userItemToAdd) => {
  const existingUserItem = users.find(
    user => user.first_name === userItemToAdd.first_name
  );

  if (existingUserItem) {
    return users.map(user =>
      user.first_name === userItemToAdd.first_name
        ? { ...user, institution: { name: user.institution.name + ', ' + userItemToAdd.institution.name } }
        : user
    );
  }

  return [...users, { ...userItemToAdd }];
};

答案 1 :(得分:1)

您要做的是某种分组,然后进行归约。 es6不提供开箱即用的groupBy功能。但是您可以使用reduce来实现相同的行为。

步骤

Source Array --> Group By Person --> Join the institution names

已实施的解决方案

在您的情况下:

const arr = [{first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
 {first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
 {first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}];


const result = arr.reduce((ac, person) => {
  // check for the existing person in the accumulator
  const existingRecord = ac.find(existingPerson => existingPerson.first_name === person.first_name)

  // if. exists, concatenate the institution
  if (existingRecord) {
    existingRecord.institution += `, ${person.institution.name}`;
    return ac;
  // otherwise, add this as a new person
  } else {
    return [...ac, {
      first_name: person.first_name,
      age: person.age,
      institution: person.institution.name
    }]
  }
}, []);

实施小组的更通用方法:

Most efficient method to groupby on an array of objects

您还可以使用 Lodash (提供更多选项)

答案 2 :(得分:0)

您可以尝试

const arr = [{first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
 {first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
 {first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}];

const result = arr.reduce((acc, item) => {
  const itemInAcc = acc.find(itemAcc => itemAcc.first_name === item.first_name && itemAcc.age === item.age);
  
  if (!itemInAcc) {
    acc.push({...item, institution: {name: item.institution.name}})
  } else {
    itemInAcc.institution.name = [itemInAcc.institution.name, item.institution.name].join(`, `)
  }
  return acc;
}, []);

console.log(result); // [{first_name: "john", age: "30", institution: {name: "inst1, inst2, inst3"}}]

答案 3 :(得分:0)

请使用以下代码。

let obj = [{
    first_name: "john",
    age: "30",
    institution: {
      id: 1,
      name: "inst1"
    }
  },
  {
    first_name: "john",
    age: "30",
    institution: {
      id: 2,
      name: "inst2"
    }
  },
  {
    first_name: "john",
    age: "30",
    institution: {
      id: 3,
      name: "inst3"
    }
  }
]
let newObj = []

let isSame = true;
let obj1 = {}
let obj2 = {}
obj.forEach((o, i) => {

  if (i + 1 < obj.length) {
    obj1 = {
      fn: obj[i].first_name,
      age: obj[i].age
    }
    obj2 = {
      fn: obj[i + 1].first_name,
      age: obj[i + 1].age
    }
    if (JSON.stringify(obj1) !== JSON.stringify(obj2) ){
    	isSame = false;
    }
  }

})

if(isSame){
let anotherobj = {}
	let fn = obj[0].first_name
  let age = obj[0].age;
  let instiValue=''
  obj.forEach(o=>{
  	instiValue = instiValue + o.institution.name + ", ";
  })
  anotherobj.first_name = fn;
  anotherobj.age = age;
  anotherobj.institution = instiValue;
  
  newObj.push(anotherobj);
}

console.log(newObj)

答案 4 :(得分:0)

这可能有帮助。

const data = [{first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
              {first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
              {first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}]

console.log(
    Object.values(
        data.reduce((p,{ institution: { name }, ...r }, _, __, k = r) =>
            ((p[k] ? (p[k].institution.name += `, ${name}`) 
                   : p[k] = ({ ...r, institution: { name }  })), p),{})))

答案 5 :(得分:0)

您可以生成将first_name和age属性组合在一起的键,并在Map Object中使用它们,然后将结果转换回数组

const items = [
    {first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
    {first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
    {first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}];

const key = item => `${item.first_name}:${item.age}`;

const unique = new Map(items.map(item => [key(item), item]))
const result = Array.from(unique.values())

答案 6 :(得分:0)

请检查此代码-

let a = [{ first_name: "john", age: "30", institution: { id: 1, name: "inst1" } },
{ first_name: "john", age: "30", institution: { id: 2, name: "inst2" } },
{ first_name: "mohan", age: "20", institution: { id: 2, name: "inst2" } },
{ first_name: "john", age: "30", institution: { id: 3, name: "inst3" } }];

let b = [];
for (var i = 0; i < a.length; i++) {
    if (b.length != 0) {

        let j_val = '';
        let flag = false;

        for (let j = 0; j < b.length; j++) {
            if ((a[i].first_name == b[j].first_name) && (a[i].age == b[j].age)) {
                j_val = j;
                flag = true;
            } else {

            }

        }
        let cc = a[i].institution.name;
        if (flag) {
            b[j_val].institution.name = b[j_val].institution.name + "," + cc;
        } else {
            b.push({ first_name: a[i].first_name, age: a[i].age, institution: { name: a[i].institution.name } });
        }
    } else {
        b.push({ first_name: a[i].first_name, age: a[i].age, institution: { name: a[i].institution.name } });
    }

}

console.log(b)