Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用ES6实现该方法 #32

Open
zhangolve opened this issue Apr 11, 2017 · 13 comments
Open

使用ES6实现该方法 #32

zhangolve opened this issue Apr 11, 2017 · 13 comments

Comments

@zhangolve
Copy link

zhangolve commented Apr 11, 2017

const obj={a:1,b:2,c:3};
function foo(o,arr){
	//请实现该方法
}

foo(obj,["a","c"]);

//输出 {a:1,c:3}

@zhangolve
Copy link
Author

坦白讲,这道题目是在一套笔试题中的最后一道,整套题目给了我一个小时完成,后来剩最后十分钟,还剩这一道题,当时也就多少有点慌了,还有就是,纯手写的话,有些思路打不开,也被他题目里特地强调的使用ES6吓到了。

const obj={a:1,b:2,c:3};
function foo(o,arr){
	var obj={};
	arr.map((i)=>obj[i]=o[i]);
	return obj;
}

foo(obj,["a","c"]);

刚刚简单实现了一下,要说有用ES6的就是箭头函数了。不知道还有哪些更好的方法。

@ucev
Copy link

ucev commented Apr 11, 2017

这种情况下用 forEach 更好吧

function foo(o, arr) {
  var obj = {};
  arr.forEach((i) => obj[i] = o[i]);
  return obj;
}

@ningt
Copy link

ningt commented Apr 12, 2017

function foo(o, arr) {
    return arr.reduce((acc, v) => {
	acc[v] = o[v];
	return acc;
    }, {});
}

@leecz
Copy link

leecz commented Apr 27, 2017

function foo (o, arr) {
  const result = {}
  Object.keys(o).filter(k => arr.includes(k)).map(s => { result[s] = o[s] })
  return result
}

@huzidaha
Copy link

大家都想得挺远...

const foo = (o, arr) => arr.reduce((ret, key) => {
  ret[key] = o[key]
  return ret
}, {})

@zhishaofei3
Copy link

我支持@zhangolve的版本

@ghost
Copy link

ghost commented Jul 27, 2017

  • let foo=(o,arr)=>{
  • let obj={};
  • arr.forEach((i)=>obj[i]=o[i]);
  • return obj;
  • }
  • foo(obj,["a","c"]);

@rianma
Copy link

rianma commented Aug 6, 2017

const foo = (obj, arr) => arr.reduce((ret, key) => Object.assign(ret, { [key]: obj[key] }), {})

不需要 return 的写法

@mqliutie
Copy link

reduce 方法用的还是少啊~~~,平时真的很少用

@bpup
Copy link

bpup commented Sep 17, 2017

const foo=(obj,arr)=>{

    var res=arr.reduce((res,cur)=>{
        res[cur]=obj[cur]
        return res
    },{})
    console.log(res)
    return res
}
const obj={a:1,b:2,c:3};
foo(obj,["a","c"]);

@wangyue57
Copy link

  let foo = (obj, arr) => JSON.parse(JSON.stringify(obj, arr))

@mqliutie
Copy link

mqliutie commented Nov 3, 2017

@Wang-NQXB 你这方法会漏情况

const obj={a:1,b:2,c:function(){console.log(123)}};

这种情况你就会把c丢掉

@liyuanqiu
Copy link

纯粹卖弄语法,娱乐一下:

function foo(...args) {
  const [o, arr] = args;
  return arr.reduce((acc, curr) => ({
    ...acc,
    [curr]: o[curr],
  }), {});
}

// test
foo({a:1,b:2,c:3}, ['a', 'c']);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests