Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i return a JSON object property

I want to do something like this:

function createParam(value, key = 'params') {
    return [key]: {value: JSON.stringify(value) ,name: ''}
}

So that i can do something like this:

const param1 = createParam(someVaue);
const param2 = createParam(someOtherValue, someKey);
const parameter = {param1, param2}

How can i do something like this?, currently i have problem with the function createParam because a syntax like the one above doesn't seem to exists.
Update 01:
Some of the answers suggested good solutions that works but just to clarify for anyone else who reads the question, the expected output for parameter is:

{key1: {value:'xx', name: ''},key2: {value:'xx', name: ''},key3: {value:'xx', name: ''},...}
like image 235
Ali Ahmadi Avatar asked Dec 14 '25 18:12

Ali Ahmadi


1 Answers

Your intended behavior is not possible. But you can try the following

function createParam(value, key = 'params') {
    return {[key]: {value: JSON.stringify(value) ,name: ''}}
}

and you can do the below using ES6 syntax

const param1 = createParam(someVaue);
const param2 = createParam(someOtherValue, someKey);
const parameter = {...param1, ...param2}

or

const param1 = createParam(someVaue);
const param2 = createParam(someOtherValue, someKey);
const parameter = Object.assign({}, param1, param2);

function createParam(value, key = 'params') {
    return {[key]: {value: JSON.stringify(value) ,name: ''}}
}
let someValue = "someValue";
let someOtherValue = "someOtherValue";
let someKey = "key1";

const param1 = createParam(someValue);
const param2 = createParam(someOtherValue, someKey);
const parameter = {...param1, ...param2}
console.log(parameter);

const param3 = createParam(someValue);
const param4 = createParam(someOtherValue, someKey);
const parameter2 = Object.assign({}, param3, param4);
console.log(parameter2);
like image 91
Aditya Avatar answered Dec 17 '25 09:12

Aditya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!