Reputation: 145
I would like to know how to change particular field by passing parameter type in javascript
I have object obj1, obj2, if the parameter type is string/array change the value field as shown in expected output and vice-versa
function ChangeObj(obj, str){
var result = obj.map(e=> str==="string" ? ({...e, value:[e.value]}) : ({...e,value: e.value.toString()}) )
return result;
}
var obj1 =[
{ key: "country", id:0, value: "SG"},
{ key: "city", id:1, value: "IN"}
]
var obj2 = [
{ key: "cn", id:0, value: ["TH","MY"],img:"sample.jpg"},
{ key: "list", id:1, value: ["AU"], img:"item.jpg" }
]
var output1 = this.ChangeObj(obj1, "array");
var output2 = this.ChangeObj(obj2, "string");
Expected Output:
//output 1
[
{ key: "country", id:0, value: ["SG"] },
{ key: "city", id:1, value: ["IN"] }
]
// output 2
[
{ key: "cn", id:0, value: "TH", img:"sample.jpg"},
{ key: "cn", id:0, value: "MY", img:"sample.jpg" },
{ key: "list", id:1, value: "AU", img:"item.jpg" }
]
Upvotes: 1
Views: 628
Reputation: 147146
Because you want to generate multiple values when converting an array to a string, you can't use map
directly. Instead, you could use reduce
and then map
the object value property inside the reduce
:
function ChangeObj(obj, str) {
var result = obj.reduce((c, o) => c.concat(str === "array" ? [{ ...o,
value: [o.value]
}] : o.value.map(v => ({ ...o,
value: v
}))), []);
return result;
}
var obj1 =[
{ key: "country", id:0, value: "SG"},
{ key: "city", id:1, value: "IN"}
]
var obj2 = [
{ key: "cn", id:0, value: ["TH","MY"],img:"sample.jpg"},
{ key: "list", id:1, value: ["AU"], img:"item.jpg" }
]
var output1 = this.ChangeObj(obj1, "array");
var output2 = this.ChangeObj(obj2, "string");
console.log(output1);
console.log(output2);
Note that the sense of your ternary conditional is wrong and I have corrected it to str === "array"
in this code.
Upvotes: 1
Reputation: 350097
Two issues:
You reversed the cases of string/array: in first case you want to wrap strings in arrays, but you pass "array" as second argument, while the function performs this wrapping when that argument is "string". So either you pass the wrong argument, or else the ternary expression should have the opposite condition.
When converting array to string you are currently applying toString
to the array. But that will not multiply the number of objects in the output. It will just produce a comma separated string in one single object.
You can still use map
to solve that last issue, but then apply a .flat
to resolve the nested array that you'll get:
obj.map(e => str !== "string"
? {...e, value: [e.value]}
: e.value.map(value => ({...e,value}) )
).flat();
Upvotes: 0