typescript 获取JavaScript中对象数组中出现的所有非唯一值

p4tfgftt  于 2023-05-01  发布在  TypeScript
关注(0)|答案(2)|浏览(108)
let input = [
  {
    id: 1,
    rollNo: 5,
    Name: "A",
    stDetails: {
      city: "city1",
      pin: 1234,
    },
  },
  {
    id: 2,
    rollNo: 5,
    Name: "B",
    stDetails: {
      city: "city1",
      pin: 1234,
    },
  },
  {
    id: 3,
    rollNo: 5,
    Name: "C",
    stDetails: {
      city: "city1",
      pin: 1234,
    },
  },
  {
    id: 4,
    rollNo: 5,
    Name: "D",
    stDetails: {
      city: "city1",
      pin: 1234,
    },
  },
  {
    id: 5,
    rollNo: 10,
    Name: "E",
    stDetails: {
      city: "city2",
      pin: 1234,
    },
  },
];
let uniqueKey = ["rollNo", "stDetails.city"];

我想得到所有非唯一值的id在一个以上的出现,并检查记录是唯一的,我们需要检查rollNostDetails.city
所以预期输出是:

[{id:2},{id:3},{id:4}];

在这里,您可以看到id 2、3和4与id 1具有相同的细节,因此这就是为什么它是预期输出

nhjlsmyf

nhjlsmyf1#

var input=[{"id":1,"rollNo":5,"Name":"A","stDetails":{"city":"city1","pin":1234}},
{"id":2,"rollNo":5,"Name":"B","stDetails":{"city":"city1","pin":1234}},
{"id":3,"rollNo":5,"Name":"C","stDetails":{"city":"city1","pin":1234}},
{"id":4,"rollNo":5,"Name":"D","stDetails":{"city":"city1","pin":1234}},
{"id":5,"rollNo":10,"Name":"E","stDetails":{"city":"city2","pin":1234}}
];
// Group by column rollNo & stDetails's city
var groupByCol=_.groupBy(input,function(x){return x.rollNo+'#'+x.stDetails.city});
var finaldata=[];
//Loop the record of grouping
_.forEach(groupByCol,function(c){
// If find match more than one then check.
if(c.length>1){
var finaldata=_.drop(_.map(c,function(x){return {"id":x.id}}))
console.log(finaldata);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

你可以这样做。

w1jd8yoj

w1jd8yoj2#

纯JS解决方案

当然,你可以使用库,但是纯库总是最好的!
你应该循环遍历input,然后保存唯一的,并将每个与uniques数组进行比较!
如果在比较对象时遇到问题,只需将其转换为JSON
如果您有任何疑问,请发表评论。..

var input=[{"id":1,"rollNo":5,"Name":"A","stDetails":{"city":"city1","pin":1234}},
{"id":2,"rollNo":5,"Name":"B","stDetails":{"city":"city1","pin":1234}},
{"id":3,"rollNo":5,"Name":"C","stDetails":{"city":"city1","pin":1234}},
{"id":4,"rollNo":5,"Name":"D","stDetails":{"city":"city1","pin":1234}},
{"id":5,"rollNo":10,"Name":"E","stDetails":{"city":"city2","pin":1234}}
];

let unique_keys = ["rollNo", "stDetails"];
let uniques = [];
let non_uniques = [];
let uic;

for (let i of input) {
  for (let u of uniques) {
    uic = unique_keys.length;
    for (let uk of unique_keys) {
      let iitem = JSON.stringify(i[uk]);
      let uitem = JSON.stringify(u[uk]);
      if (iitem == uitem && --uic == 0) break;
    }
  }
  if (uic != 0) uniques.push(i);
  else non_uniques.push(i);
}

console.log(non_uniques);

注意:如果你需要唯一的,打印uniques数组而不是non_uniques数组。

相关问题