Modify object in Javascript - javascript

I'm trying to convert object
var data = {"USD": 12323,"CAD":32123}
to become
[{"id":"USD","value":12323},{"id":"CAD","value":32123}]
This is what i tried so far
var res = Object.keys(data).map(function(k) {
return [k, result[k]];
});
and get the result
[["USD", 12323],["CAD", 32123]]
Any help is very appreciated.
Thanks,

Just change your return statement to
return {id: k, value:result[k]}; //observe that an object is returned instead of an array
Demo
var data = {"USD": 12323,"CAD":32123};
var res = Object.keys(data).map(function(k) {
return {id: k, value:data[k]};
});
console.log( res );

You're creating one array, not an object. Change [] to {}:
var res = {"USD": 12323,"CAD":32123};
res = Object.keys(res).map(function(k) {
return {id: k, value:res[k]};
});
console.log(res);
as an alternative, you can use arrow function:
var res = {"USD": 12323,"CAD":32123};
res = Object.keys(res).map(x => x = { id: x, value: res[x]});
console.log(res);
or .every():
var res = {"USD": 12323,"CAD":32123};
var resWArrow = Object.entries(res).map(function(k) {
return {id: k[0], value: k[1]};
});
console.log('Without arrow: ' + JSON.stringify(resWArrow));
var resArrow = Object.entries(res).map(x => x = { id: x[0], value: x[1] });
console.log('With arrow: ' + JSON.stringify(resArrow));

With ES6, you could take Object.entries with Array#map and a destructuring assignment for the elements and short hand properties for the result.
var data = { "USD": 12323, "CAD": 32123 },
result = Object.entries(data).map(([id, value]) => ({ id, value }));
console.log(result);

You can iterate over the keys of the object and map them like follows:
Object.keys(res).map(function(key) {
return {id: key, value: data[key]};
}

Change the return statement and return an object
var res = {
"USD": 12323,
"CAD": 32123
}
var m = Object.keys(res).map(function(item) {
return {
id: item,
value: res[item]
}
})
console.log(m)

Related

how to get array according to conditions in javascript

My array comes like this
var data=[{PRODUCT : P1}, {PRODUCT: P2}]
I wantt to convert this into [P1, P2].
Sometimes my array comes like this
var data=[{ITEM: I1, QUANTITY:1}, {ITEM: I2, QUANTITY:2}]
I wantt to convert this into [I1, I2].
so can we make a common function, where I just want to extract particular value of array and make a new array.
p.s. Thank you in advance
I tried to write the logic like this:
data.map((d, index) => { var result= [];
result.includes(d[0]); })
but it,s not dynamic
You could define a function which will always get the first value of the first object key, this should satisfy your needs based on the above
var data1 = [{
ITEM: 'I1',
QUANTITY: 1
}, {
ITEM: 'I2',
QUANTITY: 2
}]
var data2 = [{
PRODUCT: 'P1'
}, {
PRODUCT: ' P2'
}]
function getArrayOfValues(list) {
return list.reduce((acc, x) => {
const firstValue = Object.values(x)[0];
acc.push(firstValue)
return acc;
}, [])
}
const result1 = getArrayOfValues(data1)
console.log(result1)
const result2 = getArrayOfValues(data2)
console.log(result2)
function getProductOrItem(list) {
return list.reduce((accumulator, obj) => {
if (obj.PRODUCT) {
accumulator.push(obj.PRODUCT);
} else if (obj.ITEM) {
accumulator.push(obj.ITEM);
}
return accumulator;
}, [])
}
you can iterate through your array with map() method and inside it extract the value of a first entity of an object in your array and simply get a new array with all values:
const data1 =[{PRODUCT : 'P1'}, {PRODUCT: 'P2'}]
const data2 = [{ITEM: 'I1', QUANTITY: 1}, {ITEM: 'I2', QUANTITY: 2 }]
const transformValuesOfArray = (arrayToTransform) =>
arrayToTransform.map(value => {
const firstObjectValue = Object.values(value)[0]
return firstObjectValue
})
console.log(transformValuesOfArray(data1))
console.log(transformValuesOfArray(data2))

how to change an array to json object in javascript

I have an array like below
let result = ["a","b","c","d"]
then need to change like below how to do it Thank you for any help.
result = [
{
type: "a",
image: "a.jpg"
},
{
type: "b",
image: "b.jpg"
},
{
type: "c",
image: "c.jpg"
},
{
type: "d",
image: "d.jpg"
}
]
I'd use map() for this.
const objResult = result.map((item) => {
return {
type: item,
image: item + '.jpg'
};
});
You can use array .map() method to return a new object with type & image properties like:
let result = ["a","b","c","d"]
result = result.map(r => ({type: r, image: `${r}.jpg`}))
console.log( result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.forEach() and Array.push() Array methods achieve the result:
let obj = [];
let result = ["a","b","c","d"]
result.forEach(function(el, i) {
obj.push({
type: el,
image: `${el}.jpg`
})
});
console.log(obj);
You would describe your function like this -
function convertResult(result){
let ans = [];
for(var i=0; i<result.length; i++){
ans[i] = {'type': result[i], 'image': result[i]+'.jpg'};
}
return ans;
}
then you would call your function as this -
let result = ["a","b","c","d"]
let ans = convertResult(result);
Use map
let result = ["a","b","c","d"]
const map = result.map(x => ({"type":x,"image": x+".jpg"}));
console.log(map);

Refactor array of objects

The below code will have input as array of objects and I would like to convert into a different format.
The below code works fine but I need a more refactored shorter format of what I am trying to achieve.
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
var res = [];
for(var key in parsedObj.data){
var emailObj = {};
var phoneObj = {}
if(parsedObj.data[key].email !== null){
emailObj.matchedRes = parsedObj.data[key].email;
emailObj.id = parsedObj.data[key].id;
emailObj.type = "email";
res.push(emailObj);
}
if(parsedObj.data[key].phone !== null){
phoneObj.matchedRes = parsedObj.data[key].phone;
phoneObj.id = parsedObj.data[key].id;
phoneObj.type="phone";
res.push(phoneObj);
}
}
console.log(res);
Desired output:
[ { matchedRes: 'jack1#yahoo.com', id: 'jack1', type: 'email' },
{ matchedRes: 'jack.clinton#yahoo.com', id: 'jack2', type: 'email' },
{ matchedRes: '+16464922600', id: 'jack2', type: 'phone' } ]
In the above code separate objects are created with phone and email for same id.
Here is a solution!
I just did a generic reducer, and then I use it on phone and email.
Then, I just spread the result of both calls to the result array :)
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
const extractData = (obj, type) => obj.reduce((acc, elt) => (
elt[type] && acc.push({matchedRes: elt[type], id: elt.id, type: type})
, acc),[]);
const result = [...extractData(parsedObj.data, 'email'), ...extractData(parsedObj.data, 'phone')];
console.log(result);
Hope this helps, please do not hesitate to comment if you have any question ;)
You can use reduce with destructuring assignment . and check if email or phone is there than add a object accordingly
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
let op = parsedObj.data.reduce((out,{id,email,phone})=>{
if(email){
out.push({matchedRes:email,id,type:`email`})
}
if(phone){
out.push({matchesRes:phone,id,type:`phone`})
}
return out
},[])
console.log(op)
If you want to see more use cases of You can destructuring assignment and it's uses you can check this one out
This should be possible with reduce:
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
const keyFields = ["email", "phone"];
let result = parsedObj.data.reduce((acc, val) => {
keyFields.forEach(k => {
if (val[k]) acc.push({ matchedRes: val.email, id: val.id, type: k});
});
return acc;
}, []);
console.log("Result: ", result);
If you are looking for a little shorter code but still easy to read for anybody:
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
var res = [];
Object.entries(parsedObj.data).forEach(el => {
el = el[1]
if(el.email !== null)
res.push({
matchedRes: el.email,
id: el.id,
type: "email"
})
if(el.phone !== null)
res.push({
matchedRes: el.phone,
id: el.id,
type: "phone"
})
})
console.log(res);

How to merge values from multiple objects into an object of arrays?

I have a two JSON something like below:
var obj1 = {
" name ":"rencho",
" age ":23,
" occupation ":"SE"
}
var obj2 = {
" name ":"manu",
" age ":23,
" country ":"india"
}
I want the expected output:
var result = {
"name":["rencho", "manu"],
"age":[23, 23],
"country":["-", "india"],
"occupation": ["SE", "-"],
}
However, I tried using below the code snippet:
let arrGlobal = []
arrGlobal.push(obj1);
arrGlobal.push(obj2);
let mergedResult = arrGlobal.reduce(function(r, e) {
return Object.keys(e).forEach(function(k) {
if(!r[k]) r[k] = [].concat(e[k])
else r[k] = r[k].concat(e[k])
}), r
}, {})
console.log(mergedResult);
But that one doesn't print - in json object. I would appreciate any kind of help from your side.
HELP WOULD BE APPRECIATED!!!
First get a list of all keys (needed in advance to check whether you need to add - while iterating), then use reduce to iterate over each object and add its values to the accumulator:
var obj1 = {
" name ":"rencho",
" age ":23,
" occupation ":"SE"
}
var obj2 = {
" name ":"manu",
" age ":23,
" country ":"india"
}
const arr = [obj1, obj2];
const allKeys = arr.reduce((keys, obj) => {
Object.keys(obj).forEach(key => keys.add(key))
return keys;
}, new Set());
const merged = arr.reduce((merged, obj) => {
allKeys.forEach((key) => {
if (!merged[key]) merged[key] = [];
merged[key].push(obj[key] || '-');
});
return merged;
}, {});
console.log(merged);
A slightly different approach by using a single loop for the outer array of objects and which generates all needed keys on the fly.
var obj1 = { name: "rencho", age: 23, occupation: "SE" },
obj2 = { name: "manu", age: 23, country: "india" },
hash = new Set,
result = {};
[obj1, obj2].forEach((o, length) => {
Object.keys(o).forEach(k => hash.add(k));
hash.forEach(k => {
result[k] = result[k] || Array.from({ length }).fill('-');
result[k].push(k in o ? o[k] : '-');
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
quick and dirty way:
function merge(a,b) {
var c = b
for (key in a){
c[key] = [c[key], a[key]]
}
console.log(c) //prints merged object
}
merge(obj1, obj2)

Flatten a javascript object to pass as querystring

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:
{ cost: 12345, insertBy: 'testUser' } would become cost=12345&insertBy=testUser
I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as data but not in this case. Using jQuery to flatten to object would be okay though.
Thank you.
Here's a non-jQuery version:
function toQueryString(obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
}
}
return parts.join("&");
}
You want jQuery.param:
var str = $.param({ cost: 12345, insertBy: 'testUser' });
// "cost=12345&insertBy=testUser"
Note that this is the function used internally by jQuery to serialize objects passed as the data argument.
My ES6 version (pure Javascript, no jQuery):
function toQueryString(paramsObject) {
return Object
.keys(paramsObject)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
.join('&')
;
}
This is an old question, but at the top of Google searches, so I'm adding this for completeness.
If 1) you don't want to user jQuery, but 2) you want to covert a nested object to a query string, then (building off of Tim Down and Guy's answers), use this:
function toQueryString(obj, urlEncode) {
//
// Helper function that flattens an object, retaining key structer as a path array:
//
// Input: { prop1: 'x', prop2: { y: 1, z: 2 } }
// Example output: [
// { path: [ 'prop1' ], val: 'x' },
// { path: [ 'prop2', 'y' ], val: '1' },
// { path: [ 'prop2', 'z' ], val: '2' }
// ]
//
function flattenObj(x, path) {
var result = [];
path = path || [];
Object.keys(x).forEach(function (key) {
if (!x.hasOwnProperty(key)) return;
var newPath = path.slice();
newPath.push(key);
var vals = [];
if (typeof x[key] == 'object') {
vals = flattenObj(x[key], newPath);
} else {
vals.push({ path: newPath, val: x[key] });
}
vals.forEach(function (obj) {
return result.push(obj);
});
});
return result;
} // flattenObj
// start with flattening `obj`
var parts = flattenObj(obj); // [ { path: [ ...parts ], val: ... }, ... ]
// convert to array notation:
parts = parts.map(function (varInfo) {
if (varInfo.path.length == 1) varInfo.path = varInfo.path[0];else {
var first = varInfo.path[0];
var rest = varInfo.path.slice(1);
varInfo.path = first + '[' + rest.join('][') + ']';
}
return varInfo;
}); // parts.map
// join the parts to a query-string url-component
var queryString = parts.map(function (varInfo) {
return varInfo.path + '=' + varInfo.val;
}).join('&');
if (urlEncode) return encodeURIComponent(queryString);else return queryString;
}
Use like:
console.log(toQueryString({
prop1: 'x',
prop2: {
y: 1,
z: 2
}
}, false));
Which outputs:
prop1=x&prop2[y]=1&prop2[z]=2
Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:
var toQueryString = function(obj) {
return _.map(obj,function(v,k){
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
};
^ I wrote that 5 years ago. An updated and more succinct version of this would now (Oct 2019) be:
var input = { cost: 12345, insertBy: 'testUser' };
Object.entries(input)
.map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
// cost=12345&insertBy=testUser
Check that the runtime that you're targeting supports Object.entries() or that you're using a transpiler like Babel or TypeScript if it doesn't.
Try the $.param() method:
var result = $.param({ cost: 12345, insertBy: 'testUser' });
General JavaScript:
function toParam(obj) {
var str = "";
var seperator = "";
for (key in obj) {
str += seperator;
str += enncodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
seperator = "&";
}
return str;
}
toParam({ cost: 12345, insertBy: 'testUser' })
"cost=12345&insertBy=testUser"
Another version:
function toQueryString(obj) {
return Object.keys(obj).map(k => {
return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
})
.join("&");
}
var myObj = { cost: 12345, insertBy: 'testUser' },
param = '',
url = 'http://mysite.com/mypage.php';
for (var p in myObj) {
if (myObj.hasOwnProperty(p)) {
param += encodeURIComponent(p) + "=" + encodeURIComponent(myObj[p]) + "&";
}
}
window.location.href = url + "?" + param;
you can use this
function serialize(obj)
{
let str = []
for(var p in obj)
{
if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
}
return str.join('&')
}
try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/
ES6 version of Jrop's answer (also parses nested params)
const toQueryString = (obj, urlEncode = false) => {
if (!obj) return null;
const flattenObj = (x, path = []) => {
const result = [];
Object.keys(x).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(x, key)) return;
const newPath = path.slice();
newPath.push(key);
let vals = [];
if (typeof x[key] === 'object') {
vals = flattenObj(x[key], newPath);
} else {
vals.push({ path: newPath, val: x[key] });
}
vals.forEach((v) => {
return result.push(v);
});
});
return result;
};
let parts = flattenObj(obj);
parts = parts.map((varInfo) => {
if (varInfo.path.length === 1) {
varInfo.path = varInfo.path[0]; // eslint-disable-line no-param-reassign
} else {
const first = varInfo.path[0];
const rest = varInfo.path.slice(1);
varInfo.path = `${first}[${rest.join('][')}]`; // eslint-disable-line no-param-reassign
}
return varInfo;
});
const queryString = parts.map((varInfo) => {
return `${varInfo.path}=${varInfo.val}`;
}).join('&');
if (urlEncode) {
return encodeURIComponent(queryString);
}
return queryString;
};
Using Lodash library it can be done as:
let data = {}
_.map(data, (value, key) => `${key}=${value}`)
.join("&");
Note that this library has been imported as:
window._ = require('lodash');

Categories

Resources