How can I include an array into my JSON object in Javascript? - javascript

I'm trying to prepare an array into a json object to send to an API.
I'm struggling to figure out how to manipulate my array into the right shape.
My array looks something like this.
data: [
["Lisa", "Heinz", "1993-04-15" ],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
]
I'd like it to be a json object looking like this:
{person:[{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},{"name":"","last_name":"","dob":""}],"object_id":259,"test":"bob","attribute":"bob123"}
Currently I do this:
let json = {}
for (let person of formData) {
const identifier = `person${formData.indexOf(person)}`;
json[identifier] = {
name: person[0],
last_name: person[1],
dob: person[2]
}
}
json.object_id = "259";
json.wp_test = "bob";
json.attribute = "bob123";
Which outputs something like this:
{"person0":{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},"person1":{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},"person2":{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},"person3":{"name":"","last_name":"","dob":""},"object_id":259,"wp_test":"bob","attribute":"bob123"}
I've tried a variety of things to get the right shape - what's an easily understandable way to get there?

It's just a matter of matching the correct keys/indexes.
var data = [
["Lisa", "Heinz", "1993-04-15"],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
]
var persons = data.reduce(function(agg, item) {
agg.push({
name: item[0],
last_name: item[1],
dob: item[2],
})
return agg;
}, [])
var final = {
person: persons,
object_id: 259,
wp_test: 'bob',
attribute: 'bob123',
}
console.log(final)
.as-console-wrapper {max-height: 100% !important}

You can simply achieve this by iterating the input array with the help of Array.map() method.
Live Demo :
const data = [
["Lisa", "Heinz", "1993-04-15" ],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
];
const jsonObj = {};
jsonObj.person = data.map(arr => ({ name: arr[0], last_name: arr[1], dob: arr[2] }));
jsonObj.object_id = "259";
jsonObj.wp_test = "bob";
jsonObj.attribute = "bob123";
console.log(jsonObj);

Related

Array of objects to comma separated array javascript

I'm trying to convert array of objects to comma separated string array.
Input:
report: [{"name":"abc","age":23,"gender":"male"},
{"name":"def","age":24,"gender":"female"},
{"name":"ghi","age":25,"gender":"other"}]
Expected Output:
[["abc",23,"male"],["def",24,"female"],["ghi",25,"other"]]
Code:
resultArray: any = [];
report.forEach(d => {
var energy = Object.values(d).join(",");
this.resultArray.push([energy]);
});
Result: [["abc,23,male"],["def,24,female"],["ghi,25,other"]]
Where am i wrong?
join(',') will join array separated by , and you are assigning it in array as:
this.resultArray.push([energy]);
All you have to do is:
var energy = Object.values(d); // get all the values of an object
this.resultArray.push(energy); // Pust energy values in resultArray
const report = [
{ name: 'abc', age: 23, gender: 'male' },
{ name: 'def', age: 24, gender: 'female' },
{ name: 'ghi', age: 25, gender: 'other' },
];
const resultArray = [];
report.forEach((d) => {
var energy = Object.values(d);
resultArray.push(energy);
});
console.log(resultArray);
With .join(','), you're turning each object you're iterating over into a single string. If you want 3 separate elements, don't join.
const report = [{"name":"abc","age":23,"gender":"male"},
{"name":"def","age":24,"gender":"female"},
{"name":"ghi","age":25,"gender":"other"}]
const resultArray = [];
report.forEach(d => {
var energy = Object.values(d);
resultArray.push(energy);
});
console.log(resultArray);
Or, better:
const report = [{"name":"abc","age":23,"gender":"male"},
{"name":"def","age":24,"gender":"female"},
{"name":"ghi","age":25,"gender":"other"}]
const resultArray = report.map(Object.values);
console.log(resultArray);

Unstring an object property name javascript

I have an object similar to this:
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
I want to transfrorm every property name that is a string into a non-string one, like this:
const obj = {
id: 1,
name: {
english_us: "John",
english_uk: "John",
italian_eu: "Giovanni",
},
};
I can't modify the original object. I get it from an axios request.
You could use regex with stringify
let output = JSON.parse(JSON.stringify(obj).replace(/"(.*?)":.*?,?/g,
key=>key.replace(/\-/g, `_`)));
Output
console.log(JSON.stringify(output, null, 4));
/*
{
"id": 1,
"name": {
"english_us": "John",
"english_uk": "John",
"italian_eu": "Giovanni"
}
}*/
If you can copy the object, you could check this solution for declaring the attributes:
link
There are a few ways of achieving this. This example has a function that converts the key on every iteration of the name entries. A new names object is updated with these properties, and is later folded into a new object along with the existing properties of the original object.
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
const convert = (key) => key.replace('-', '_');
const updatedName = {};
for (const [key, value] of Object.entries(obj.name)) {
updatedName[convert(key)] = value;
}
const newObj = { ...obj, name: updatedName };
console.log(newObj);
You can convert object to JSON and convert back.
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
console.log(JSON.parse(JSON.stringify(obj)))
Two ways to clone the object and rename all keys from its name property
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
// clone obj
const myObj = window.structuredClone ?
structuredClone(obj) : JSON.parse(JSON.stringify(obj));
// rename all keys in myObj.name
Object.keys(myObj.name).forEach(key => {
myObj.name[key.replace(/\-/g, `_`)] = myObj.name[key];
delete myObj.name[key];
});
console.log(myObj.name.english_us);
// obj is untouched
console.log(obj.name[`english-us`]);
// myObj.name[`english-us`] does not exist
console.log(myObj.name[`english-us`]);
// alternative: clone and rename in one go
const myObjClone = {
...obj,
name: Object.fromEntries(
Object.entries(obj.name)
.reduce( (acc, [k, v]) =>
[ ...acc, [ k.replace(/\-/g, `_`), v ] ] , [] ) )
};
console.log(myObjClone.name.italian_eu);
// obj is untouched
console.log(obj.name[`italian-eu`]);
// myObjClone.name[`italian-eu`] does not exist
console.log(myObjClone.name[`italian-eu`]);

How to merge the key-value pairs of two json arrays? - Javascript

I have two JSON arrays like this. I want to merge their keyvalue pairs. They are some items which are common in both while they are some items which are uncommon.
var jsonData1 = [
{
firstName: "Sam",
age: "10"
},
{
firstName: "John",
age: "11"
},
{
firstName: "Jack",
age: "12"
},
{
firstName: "Pam",
age: "13"
},
{
firstName: "Tom",
age: "14"
},
{
firstName: "Mitch",
age: "15"
}
];
var jsonData2 = [
{
firstName: "Sam",
city: "London"
},
{
firstName: "John",
city: "New York"
},
{
firstName: "Jack",
city: "Paris"
},
{
firstName: "Pam",
city: "Moscow"
},
{
firstName: "Roger",
city: "Shanghai"
},
{
firstName: "Don",
city: "Jakarta"
}
];
As you can there are some firstName in 1st array which does not have city in 2nd array. Again there are some firstName in 2nd array which does not have city in 1st array.
I need to club these 2 array into one array, in case a firstName does not have age or city it will be assigned '' (blank string).
The new array will have 3 fields, there are some items which will be having values in 2 fields. They have a one field as blank string.
I want to do this using Vanilla JS, I do not want to use Jquery, Lodash and Underscore.
There are a number of ways to approach this, however one option would be to base this around the Array#reduce() method as follows:
const jsonData1=[{firstName:"Sam",age:"10"},{firstName:"John",age:"11"},{firstName:"Jack",age:"12"},{firstName:"Pam",age:"13"},{firstName:"Tom",age:"14"},{firstName:"Mitch",age:"15"}];
const jsonData2=[{firstName:"Sam",city:"London"},{firstName:"John",city:"New York"},{firstName:"Jack",city:"Paris"},{firstName:"Pam",city:"Moscow"},{firstName:"Roger",city:"Shanghai"},{firstName:"Don",city:"Jakarta"}];
/*
Use Array#concat() to combine both input arrays before performing
the merge. This will ensure that all items in both arrays are
processed and accounted for during the merge (which is important in
situations where the input arrays differ in length).
Object.values() is used to transform the dictionary resulting from
reduce() to an array
*/
var result = Object.values(
[].concat(jsonData1, jsonData2
).reduce((dict, item) => {
/*
We use Array#reduce is an intermediate step to construct a dictionary
which maps each unique "item.firstName" to a corresponding object
that contains the merged (or yet to be merged) data for this first
name
*/
var value = dict[item.firstName] || {}
/*
Use Object.assign() to merge existing data for "item.firstName" with
current item being processed. Also pass default values as first
argument to ensure all three key values are present in merge result
*/
value = Object.assign({ firstName : '', age : '', city : ''} , value, item)
/*
Update the dictionary with merged data
*/
dict[item.firstName] = value
return dict
}, {}))
console.log(result);
One possible approach:
const jsonData1=[{firstName:"Sam",age:"10"},{firstName:"John",age:"11"},{firstName:"Jack",age:"12"},{firstName:"Pam",age:"13"},{firstName:"Tom",age:"14"},{firstName:"Mitch",age:"15"}];
const jsonData2=[{firstName:"Sam",city:"London"},{firstName:"John",city:"New York"},{firstName:"Jack",city:"Paris"},{firstName:"Pam",city:"Moscow"},{firstName:"Roger",city:"Shanghai"},{firstName:"Don",city:"Jakarta"}];
const result = [].concat(jsonData1, jsonData2).reduce((acc, ele) => {
const existing = acc.find(x => x.firstName === ele.firstName);
if(!existing) return acc.concat({firstName: ele.firstName, city: ele.city || '', age: ele.age || ''});
Object.keys(ele).forEach(x => existing[x] = ele[x]);
return acc;
},[])
console.log(result);
I realize you've already accepted an answer but I figured I could provide an alternative, be it better or worse.
var jsonData1 = [{firstName: "Sam",age: "10"},{firstName: "John",age: "11"},{firstName: "Jack",age: "12"},{firstName: "Pam",age: "13"},{firstName: "Tom",age: "14"},{firstName: "Mitch",age: "15"}];
var jsonData2 = [{firstName: "Sam",city: "London"},{firstName: "John",city: "New York"},{firstName: "Jack",city: "Paris"},{firstName: "Pam",city: "Moscow"},{firstName: "Roger",city: "Shanghai"},{firstName: "Don",city: "Jakarta"}];
var defaults = {firstName: "", age: "", city: ""};
var data = [ ...jsonData1, ...jsonData2 ];
var names = [ ...new Set(data.map(i=>i.firstName)) ];
var res = names.map(n => data
.reduce((acc, jd) => jd.firstName === n ? {...acc, ...jd} : acc, defaults)
);
console.log(res);
var data combines the two arrays of data into one using spread syntax (array literals).
var names creates an array of unique names using Set.
map() iterates over the list of names, creating a single, merged object for each. That merge is done using reduce() and spread syntax (object literals).

How to concat string properties of an array in an array of arrays and create a new property in each array

I have an array of arrays which looks like below:
UserList=[
[name:"user1", type:"admin", location:"NY", expired:"NO"],
[name:"user2", type:"poweruser", location:"CO", expired:"NO"],
[name:"user3", type:"admin", location:"SF", expired:"NO"],
]
I want to add the three properties name, type and location and create a new property in each individual array like the property "AllProps" in the below example:
Desired Output:
UserList=[
[name:"user1", type:"admin", location:"NY", expired:"NO",AllProps:"user1adminNY"],
[name:"user2", type:"poweruser", location:"CO", expired:"NO",AllProps:"user1poweruserCO"],
[name:"user3", type:"admin", location:"SF", expired:"NO", AllProps:"user1adminSF"],
]
Can I do this using Loadash? What is the best and fastest way to do this?
You are using {} but it should be [] for array. Also you need to use : instead of = in objects
var userList= [
{name: "user1", type: "admin", location: "NY", expired: "NO"},
{name: "user2", type: "poweruser", location: "CO", expired: "NO"},
{name: "user3", type: "admin", location: "SF", expired: "NO"}
];
var output = userList.map(user => {
user.AllProps = user.name + user.type + user.location;
return user;
});
// Short hand
var output = userList.map(user => ({ ...user, AllProps: user.name + user.type + user.location}));
console.log('output:', output);
Based on your requirements and wanting to just modify your existing array without return a new one, simply iterate the array and add the key/value pair:
var UserList = [
{name: "user1", type: "admin", location: "NY", expired: "NO"},
{name: "user2", type: "poweruser", location: "CO", expired: "NO"},
{name: "user3", type: "admin", location: "SF", expired: "NO"},
];
UserList.forEach(function(x){
x["AllProps"] = x.name + x.type + x.location;
});
console.log(UserList);
The upvoted answer will work fine, but there is no need to return anything.
I think something like this is that you need:
_.forEach(UserList, function(u){
var allPropValues = "";
_.forOwn(u, function(value, key) {
if(key !== 'expired') {
allPropValues += value;
}
});
u.AllProps = allPropValues;
});
var UserList=[
{name:"user1", type:"admin", location:"NY", expired:"NO"},
{name:"user2", type:"poweruser", location:"CO", expired:"NO"},
{name:"user3", type:"admin", location:"SF", expired:"NO"},
];
console.log({before: UserList});
_.forEach(UserList, function(u){
var allPropValues = "";
_.forOwn(u, function(value, key) {
if(key !== 'expired') {
allPropValues += value;
}
});
u.AllProps = allPropValues;
});
console.log({after: UserList});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.9/lodash.js"></script>

Combining JavaScript Arrays

I would like to take a JavaScript object that is formatted like:
results = {
names: [
"id",
"first_name"
],
values: [
[
1234,
"Fred"
],
[
4321,
"Joe"
],
[
1123,
"Mary"
]
]
}
and turn into this:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
I tried doing something like this, but I can't get the structure correct:
var data = []
for (i=0; i < results['values'].length; i++ ){
var innerData = []
for (b=0; b < results['names'].length; b++ ){
innerData.push([name:results['names'][b], value: results['values'][i][b]])
}
data.push(innerData)
}
console.log(data)
Problem 1:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
and
var data = []
and
[name:results['names'][b]…
An array [] consists a set of values in order.
An object {} consists of a set of key:value pairs.
You are using the wrong one each time. Use {} where you have [] and vice versa
Problem 2:
You say you want objects with id and name keys, but you are trying to create name and value keys. Use the property names you actually want.
Try this:
var data = [];
for (i in results['values']){
var innerData = {}
var value = results['values'][i];
for (b in value){
var key = results['names'][b];
innerData[key] = value[b];
}
data.push(innerData);
}
console.log(data);

Categories

Resources