【问题标题】:Javascript Object array parsing issueJavascript对象数组解析问题
【发布时间】:2016-07-26 06:49:38
【问题描述】:

我在 Javascript 中有以下对象:

Array[11]
0:"532"
1:"text-warning"
2:"51"
3:"text-warning"
4:"16"
5:"muted"
6:"35"
7:"text-warning"
8:"38"
9:"text-warning"
10:"106"

Array[11]
0:"533"
1:"text-warning"
2:"51"
3:"text-warning"
4:"16"
5:"muted"
6:"35"
7:"text-success"
8:"38"
9:"text-warning"
10:"106"

Array[11]
0:"534"
1:"text-warning"
2:"51"
3:"text-warning"
4:"16"
5:"text-warning"
6:"35"
7:"text-success"
8:"38"
9:"text-warning"
10:"106"

我想解析它并找出两个值在这个数组中是否只存在一次。

示例:如果 EXIST ONCE 返回数组,则为“text-success”或“muted”

如果 EXIST 两次返回 null

如果为真则返回对应的id

在上面的例子中:

第一个数组:是真的

Array[11]
0:"532"
1:"muted"
2:"35"

第二个是 FALSE,因为它存在两次

第三个:也是正确的

Array[11]
0:"534"
1:"text-success"
2:"38"

这几天一直在尝试,没有成功

我有以下 JQUERY:但它只获取唯一值而丢弃其他值:

我还需要第一个 id 和对应的 id:

Array[11]
0:"534" -> main id (needed)
1:"text-success"
2:"38" ->  company id (needed)



function singles( array) {
    for( var index = 0, single = []; index < array.length; index++ ) { 

        if(array[index] == "text-success" || array[index] == "muted") {
            single.push(array[index]);
        }
    }
    return single;
};

需要的结果或输出:

  Array[11]
    0:"532",
    1:"muted",
    2:"35",

第一个值是主 ID, 第二个值是唯一的并且 第三个值是唯一值对应的ID。

【问题讨论】:

  • 你的 jQuery 在哪里?
  • 请将对象/数组添加为文本字面量。
  • @choz 在那里,请看一下
  • @NinaScholz 你是什么意思?
  • 类似var o = { a: "foo", b: 42, c: {} };

标签: javascript arrays parsing unique


【解决方案1】:

你可以解决:

  • 对象转数组
  • 检查重复的元素然后通过
  • 唯一元素推入新数组
var obj = {
0:"532",
1:"text-warning",
2:"51",
3:"text-warning",
4:"16",
5:"muted",
6:"35",
7:"text-warning",
8:"38",
9:"text-warning",
10:"106"
};


function restUnique(obj){
 var mix = [];
 var output= [];
 Object.keys(obj).forEach(function(key) {

    mix[key]=obj[key];

 });

 for(var i in mix){
  fb=mix.indexOf(mix[i]);
  fa=mix.lastIndexOf(mix[i]);
  if(fb===fa){output.push(mix[i]);}
 }
return output;
}
// usage example:
restUnique(obj); // output : 532,51,16,muted,35,38,106

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2018-10-18
    • 2016-07-08
    • 2014-08-23
    • 1970-01-01
    • 2011-06-10
    • 2014-12-02
    相关资源
    最近更新 更多