-2
const json = {
  a: 1,
  b: 2,
  c: "HI"
}

Is there a way to just pass in {a : 1} to function?

var someReturn = aOnly({a : json.a});

I am not sure if destructuring/constructuring of ES6 solves this problem. I can't seem to find the right syntax after reading several ES6 destructuring example.

EDIT Nothing is wrong with the code I am just asking if there is a syntax to just extract "a" only from JSON without redundantly doing

{a : json.a }

the implementation of aOnly function is not the focus here

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
Zanko
  • 3,535
  • 3
  • 21
  • 41
  • In your example, what are you wanting someReturn to equal/ what do you want aOnly to return? – Joe Lissner May 02 '17 at 21:54
  • i mean... you've given one option. What's wrong with it? It's easy to read, clean, etc. – Kevin B May 02 '17 at 21:54
  • @KevinB nothing is wrong : ) Just curious is there is ES6 syntax to shorten the extraction of `{a : json.a}` – Zanko May 02 '17 at 21:58
  • `const {a} = json;aOnly({a});` but... that's no shorter than what you're doing currently, and isn't as easy to read imo. (unless you're already benefitting from destructuring `json` elsewhere) – Kevin B May 02 '17 at 22:04
  • @KevinB thanks! I just posted the answer myself. I know what I was doing wrong now. – Zanko May 02 '17 at 22:16
  • JSON and JavaScript objects are two different things. – Felix Kling May 03 '17 at 03:16

2 Answers2

2

You can use ES6 object destructuring on object passed as parameter to pick specific property.

const json = {
  a: 1,
  b: 2,
  c: "HI"
}

function aOnly({a}) {
  return a;
}

var someReturn = aOnly(json);
console.log(someReturn)
Nenad Vracar
  • 102,378
  • 14
  • 116
  • 136
  • Yes this is what I am trying to ask : P But instead of modifying `function aOnly(a) {` to `function aOnly({a}) {` is there a way to "construct" a only instead from the function call? e.g `var someReturn = aOnly ({json.a})` or something similar? – Zanko May 02 '17 at 22:01
0

Thank you I have figured out the right syntax. The initial mistake I was doing was trying to construct directly using { json.a }, hoping that this will automatically turn into { a : json.a} but the right way is do destruct first and construct later.

var json = {
    a : "ASDF",
    b : 123,
    c : "Test"
 };
 
const {a, b, c} = json; // destructing

var aObject = aOnly({a}); // constructing
var bObject = bOnly({b});
var cObject = cOnly({c});

console.log (aObject);
console.log (bObject);
console.log (cObject);

function aOnly(a) { return a; }
function bOnly(b) { return b; }
function cOnly(c) { return c; }
Zanko
  • 3,535
  • 3
  • 21
  • 41