nunnly / everycode

Javascript 每日一练
116 stars 26 forks source link

2014年11月21日 #7

Open nunnly opened 10 years ago

nunnly commented 10 years ago

嘿嘿,强化一下之前的题目。 完成该方法,根据传进去的对象,返回所有keyidvalue,记得要独立完成哟~

function extractIds(data){
    return []
}

var data = {
  id: 1,
  items: [
    {id: 2},
    {id: 3, items: [
      {id: 4},
      {id: 5}
    ]}
  ]
}
extractIds(data) // should return [1,2,3,4,5]
XadillaX commented 10 years ago
function extractIds(data) {
    var res = [];
    for(var key in data) {
        if(typeof data[key] === "object") {
            extractIds(data[key]).forEach(function(id) { res.push(id); });
        }
    }
    if(data.id !== undefined && typeof data.id !== "object") res.unshift(data.id);
    return res;
}

先上一个最圡版。

会自动忽略如下情况:

{ id: { a: 1, id: { id: 1 } } }

也就是说只取 id 不为 object 的值。

XadillaX commented 10 years ago

来个正则版的:

function extractIds(data) {
    return JSON.stringify(data, true, 2).match(/\n\s*"id":\s*.*,?/g).reduce(function(res, p) {
        return "[{".indexOf(p[p.length - 1]) !== -1 ?
            res :
            (res.push(JSON.parse("{" + p + (p[p.length - 1] === "," ? "\"_\":1}" : "}")).id), res);
    }, []);
}
nunnly commented 10 years ago

@XadillaX 妖孽,哪里逃!!!

Sanford2020 commented 10 years ago

@XadillaX 大神,大神!!!

sweet-zone commented 10 years ago
function extractIds(data) {
  for(var i in data) {
    if(i == 'id') {
      console.log(data[i]);
    }else if(data[i] instanceof Array) {
      for(var j = 0; j < data[i].length; j++) {
        extractIds(data[i][j])
      }
    }else if(data[i] instanceof Object) {
        extractIds(data[i]);
    } 
  }
}

不知道这样写好不好。。。。

jssl915 commented 10 years ago
var arr = [];
function extractIds(data){ 
  for(var key in data){typeof data[key]!== "object" ? key==='id'&&(arr.push(data[key])): extractIds(data[key])}
  return arr;
}
console.log(extractIds(data));

如果有错,谢谢指出~

nunnly commented 10 years ago
function extractIds(data){
    var str = JSON.stringify(data);
    var reg = /\"id\":([^,])/g;
    var arr =[];
    while(match = reg.exec(str)){
        arr.push(parseInt(match[1]));
    }
    return arr;
}
scarletcc commented 10 years ago
function extractIds(data){
    var ret = [];
    var switchs = function(data) {
        if(typeof data == 'object') {
            handlerObj(data);
        }else if(typeof data == 'array') {
            handlerArr(data);
        }
    }
    var handlerObj = function(data) {
        for(var o in data) {
            if(o == 'id') {
                ret.push(data[o]);
            }else {
                switchs(data[o]);
            }

        }
    }
    var handlerArr = function(data) {
        for(var i=0; i<data.length; i++) {
            switchs(data[i]);
        }
    }
    switchs(data);

    console.log(ret)
    return ret;
}

虽然感觉办法有点笨,还是贴出来吧

nunnly commented 10 years ago

嗯,思路对了就好,我帮你加了个代码样式哦,

三个1左边的点+javascript 开头,三个1左边的点结束会有代码效果

scarletcc commented 10 years ago

thank you!

XadillaX commented 10 years ago

@jssl915 多次调用呢?

XadillaX commented 10 years ago

@nunnly 你没说 id 一定是整数啊 -。-

soulcm commented 10 years ago

@XadillaX 真大神啊

soulcm commented 10 years ago

@nunnly 你的正则只能匹配一位数字,id:15的话 就只能匹配到第一个数字了

jssl915 commented 10 years ago

@Xadillax 再套一层了~~

function  extractIds(data){  
  var arr = [];
  ex(data);
  function ex(data){
    for(var key in data){typeof data[key]!== "object" ? key==='id'&&(arr.push(data[key])): ex(data[key])}
  }  
  return arr;
}
console.log(extractIds(data),extractIds(data));
zlbchapman2008 commented 10 years ago

To :nunnly {“id”:1,{'id':2,id:3}} /\"id\":([^,])/g;这个表达式应该只能匹配出 "id":1? 修改为: ((?<=\"id\":).(?=(,|})))|((?<=id:).(?=(,|})))|((?<=\'id\':).(?=(,|}))) 测试输入: { "id":1,{id:2,{'id':3}}} 输出:1,2,3

woodleaf commented 10 years ago

var values=[]; function extractIds(data){ var child; if(data.proto.constructor==Object){ child=Object.keys(data); } else{ child=data; }
for(var i=0;i<child.length;i++){ if(child[i]=="id"){ values.push(data[child[i]]); } else if(data[child[i]]&&data[child[i]].proto.constructor==Array){ arguments.callee(data[child[i]]); } else if(child[i].proto.constructor==Object){ arguments.callee(child[i]); } } } document.write(values); //[1,2,3,4,5]

singone commented 10 years ago

function extractIds(data,id){ var arr=[]; id=id||'id'; for(var i in data){ if(data.hasOwnProperty(i)){ if(i==id){ arr.push(data[i]); }else if(typeof data[i] == 'object'){ arr=arr.concat(extractIds(data[i],id)); } } } return arr }