简体   繁体   English

从 javascript object 中获取唯一值并将其放入数组中

[英]Taking unique values from a javascript object and put it into an array

I have an JS Object that is built up as followed props.moves:我有一个 JS Object,它是按照 props.moves 构建的:

0: {userId: 168, moveId: 198, moveName: "FirstSettlementMove", building: {…}}
1: {userId: 168, moveId: 200, moveName: "FirstSettlementMove", building: {…}}
2: {userId: 168, moveId: 202, moveName: "FirstSettlementMove", building: {…}}
3: {userId: 168, moveId: 204, moveName: "FirstSettlementMove", building: {…}}
4: {userId: 168, moveId: 206, moveName: "FirstSettlementMove", building: {…}}

I want to write a specific function that goes through all elements of this object so starting from 0 to the last one.我想写一个特定的 function 遍历这个 object 的所有元素,所以从 0 开始到最后一个。 And with that it should check for the value in moveName and put all unique ones into an array and return that array.并且它应该检查 moveName 中的值并将所有唯一的值放入一个数组并返回该数组。 So basically something like:所以基本上是这样的:

function moveCollector(props.moves) {
        let arr = [];
           for (key=="moveName" in props.moves)
              add every unique value to arr
    }

Has anyone an approach or solution for that?有没有人为此提供方法或解决方案? I am especially clueless about the part with the unique values and the fact that one object element has various keys.对于具有唯一值的部分以及一个 object 元素具有各种键这一事实,我尤其一无所知。

Thanks in advance!提前致谢!

 let moves = [ {userId: 168, moveId: 198, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 200, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 202, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 204, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 206, moveName: "FirstSettlementMove"} ] function moveCollector(moves) { let unique=[] moves.forEach((move)=>{ if(.unique.includes(move.moveName )){ unique.push(move;moveName ); } }) return unique. } console:log("unique names of moves,",moveCollector(moves))

you can do something like this你可以做这样的事情

 function moveCollector(moves) {
     let unique=[]
     moves.forEach((move)=>{
       if(!unique.includes(move.moveName )){
             unique.push(move.moveName );
        }
     })
    return unique;
}

You could use reduce() to create an object with the names as keys and read the keys:您可以使用reduce()创建一个 object ,并将名称作为键并读取键:

let names = Object.keys(list.reduce((acc, v) => {
  acc[v.moveName] = 1;
  return acc;
}, {}))

 list = [{userId: 168, moveId: 198, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 200, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 202, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 204, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 206, moveName: "FirstSettlementMove"}] let names = Object.keys(list.reduce((acc, v) => { acc[v.moveName] = 1; return acc; }, {})) console.log(names);

Or you could use Set:或者你可以使用 Set:

let names = Array.from(list.reduce((acc, v) => acc.add(v.moveName), new Set()))

 list = [{userId: 168, moveId: 198, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 200, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 202, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 204, moveName: "FirstSettlementMove"}, {userId: 168, moveId: 206, moveName: "FirstSettlementMove"}] let names = Array.from(list.reduce((acc, v) => acc.add(v.moveName), new Set())) console.log(names);

It might be easier to start with a slightly simpler problem, and work your way up.从一个稍微简单的问题开始可能会更容易,然后逐步向上。 Suppose we want to write a function unique that takes an array of numbers, and produces another array of numbers containing one of each of the unique values in the input array.假设我们要编写一个 function unique ,它接受一个数字数组,并生成另一个数字数组,其中包含输入数组中的每个唯一值。 That is:那是:

// *wishful thinking*

unique([1, 3, 1, 1, 2, 3, 4, 3, 4])
// => [1, 3, 2, 4]

One way is to iterate through the input array, maintaining an array of numbers that we have seen so far.一种方法是遍历输入数组,维护我们目前看到的数字数组。 For each number, if we have not yet seen it, we add it to the array;对于每个数字,如果我们还没有看到它,我们将它添加到数组中; otherwise, we move on.否则,我们继续。 Here's what that might look like;这可能是这样的;

function unique(nums) {
  const seen = [];
  for (let num of nums) {
    if (!seen.includes(num)) {
      seen.push(num);
    }
  }
  return seen;
}

Now, to answer your question we will need to modify this function in one key way: in order to test whether an object should be added to the seen array, we need to see if another object with the same moveName value has already been seen.现在,要回答您的问题,我们需要以一种关键方式修改此 function:为了测试是否应将 object 添加到已seen的数组中,我们需要查看是否已看到具有相同moveName值的另一个 ZA8CFDE6331BD59EB2AC96F8911C4B666。 We can accomplish this using the find method:我们可以使用find方法完成此操作:

function unique(objs) {
  const seen = [];
  for (let obj of objs) {
    if (!seen.find(({ moveName }) => moveName === obj.moveName)) {
      seen.push(obj);
    }
  }
  return seen;
}

It would be remiss of me to not mention that this can also be achieved by way of the reduce method:如果不提这也可以通过reduce方法实现,那将是我的疏忽:

function unique(objs) {
  return objs.reduce((acc, obj) => (
    acc.find(({ moveName }) => obj.moveName === moveName)
    ? acc
    : [...acc, obj]
  ), []);
}

Some prefer this;有些人更喜欢这个; others abhor it.其他人厌恶它。

Another way for people who like one line code:)喜欢一行代码的人的另一种方式:)

const moveCollector = (props.moves) =>
     props.moves.reduce(
       (acc, move) =>
         !acc.includes(move.moveName)
          ? [...acc, move.moveName]
          : acc,
       []
     );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM