最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

object - What's the JavaScript syntax to cast and destructure a param? - Stack Overflow

programmeradmin2浏览0评论

This seems like a stupid question. Say I have a function which accepts an object. How can I cast that object as props, but also destructure props.id to id (in the parameter declaration)?

function go ({ id }) {
  const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});

This seems like a stupid question. Say I have a function which accepts an object. How can I cast that object as props, but also destructure props.id to id (in the parameter declaration)?

function go ({ id }) {
  const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});

Share Improve this question edited Mar 21, 2019 at 6:10 neaumusic asked Mar 20, 2019 at 23:38 neaumusicneaumusic 10.5k11 gold badges59 silver badges86 bronze badges 4
  • 5 You cannot. Keep props as an argument then const { id } = props; – zerkms Commented Mar 20, 2019 at 23:39
  • Your code works when I try it. – Barmar Commented Mar 20, 2019 at 23:42
  • 2 Zerkms has the best answer, but if you don't care about code quality and you know the go function won't receive extra parameters, you can do function go(props, {id}=props) – Khauri Commented Mar 20, 2019 at 23:45
  • 1 @KhauriMcClain that's a dirty hack but I genuinely like it! :-) – zerkms Commented Mar 20, 2019 at 23:56
Add a ment  | 

2 Answers 2

Reset to default 6

You can't do it - just keep props as an argument as well to make this code simpler and easier to read:

function go (props) {
  const { id } = props;
  console.log('props', props, 'id', id);
}

go({id: 2});

You can follow this approach which names a param as props and destructures that param to extract the value of Id.

The problem es when you need to pass an additional param.

function go (props, {id} = props) {
  //const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});

发布评论

评论列表(0)

  1. 暂无评论