JSON data currently looks like this string:
["ID","Name","Age"],["212","David","38"]
And I would like for it to look like this:
{"ID":"212","Name":"David","Age":"38"}
Thanks for your help in advance
I found this code and it solves most of the issue
var columns = ["ID", "Name", "Age"];
var rows = ["212", "David", "38"];
var result = rows.reduce(function(result, field, index) {
result[columns[index]] = field;
return result;
}, {})
console.log(result);
You could do that with following steps:
extract keys and values from array
zip them to key match value
use Object.fromEntries to create object key-value
let obj = [["ID","Name","Age"],["212","David","38"]]
let [keys, values] = obj;
let zipped = keys.map((key, i)=>[key, values[i]]);
let output = Object.fromEntries(zipped);
console.log(output);
lets say
let jsonVal = [["ID","Name","Age"],["212","David","38"], ["212","David","38"]]
0th index will have the keys and remaining is data
let newJsonVal = []
for (let i =1; i< jsonVal.length-1; i++) {
let newObject ={}
jsonVal[i].map((d,j) => {
newObject[jsonVal[0][j] = d;
})
newJsonVal.push(newObject)
}
newJsonVal will have array of object as you need
Related
I have a string that needs to be converted to an object. But the string has the duplicated items. Since JSON Objects cannot contain 2 items with the same key. The second item is overwriting the first item.
How to merge the duplicate items and push to an array?
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var stringMod = string.split("&");
var stringObj = {};
stringMod.forEach(function(json) {
var jsonSplit = json.split("=");
stringObj[jsonSplit[0]] = [jsonSplit[1]];
});
console.log(stringObj,'stringObj');
Desired output:
{
"test-1": ["owner","driver"],
"test-2": ["Yes"],
"test-3": ["2"],
"test-4": ["sun","moon"],
"test-5": ["not-agree"],
"test-6": ["dogs","testing+js+object"],
"test-7": ["Testing+js+function","Testing+js+array"]
}
Here is the link to working fiddle: https://jsfiddle.net/sjoh9rqp/
Can you help me how to accomplish this ?
You can use a URLSearchParams to accomplish this, since it treats the string as url parameters it does do decoding though.
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var data = new URLSearchParams(string);
var obj = {};
for (let x of data.keys()){
obj[x] = data.getAll(x);
}
console.log(obj);
Using URLSearchParams to parse the query string helps simplify this
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
const params = new URLSearchParams(string),
res = {};
params.forEach((v,k)=> {
res[k] = res[k] || []
res[k].push(v);
})
console.log(res)
For variety, here's the answer solved with reduce(), though I have to admit URLSearchParams is more elegant
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
let obj = string.split('&').reduce((b,a) => {
let t = a.split('=');
if (b.hasOwnProperty(t[0])) b[t[0]].push(t[1]);
else b[t[0]] =[t[1]];
return b;
},{});
console.log(obj)
What is Wrong in below code? getting last index value.in all JSON Object
let arr = ['apple','banana','cherry'];
let dataJson=[];
let json={}
console.log('lent',arr.length);
for(var i = 0; i<arr.length;i++) {
json.name=arr[i];
json.type="fruit";
dataJson.push(json);
}
You are passing the object reference within the array. In the last iteration the object will have cherry which is reflected in all objects passed within the array. Instead, use Object.assign to create new object.
let arr = ['apple','banana','cherry'];
let dataJson=[];
let json={}
for(var i = 0; i<arr.length;i++) {
json.name=arr[i];
json.type="fruit";
dataJson.push(Object.assign({}, json));
}
console.log(dataJson);
You can achieve the same functionality using reduce.
let fruits = ['apple','banana','cherry'];
const output = fruits.reduce((a, fruit) => {
a.push({"name": fruit, type: "fruit"});
return a;
}, []);
console.log(output);
I would use map to do it
const arr = ['apple','banana','cherry']
const dataJson = arr.map(fruitName => ({name: fruitName, type: 'fruit'}))
console.log(dataJson)
It looks like you're trying to convert your array of string fruit names in to a JavaScript Object. Currently, your code is always overwritting the name property with every iteration. I would suggest pushing an object in every iteration instead.
let arr = ['apple','banana','cherry'];
let dataJson = [];
console.log('lent',arr.length);
for(var i = 0; i <arr.length; i++) {
dataJson.push({name: arr[i], type: 'fruit'} )
}
console.log(dataJson);
// Modern way of doing it with Array.map
const data = ['apple','banana','cherry'].map( d => ( { name: d, type: 'fruit' } ) );
console.log(data);
In other news, JSON is a string. You're working with a JavaScript Object.
I have 2 arrays namely,
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];
I want to store the values as a key value pair in another array, something like this:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
Kindly note that the array values are dynamic, so I cannot hardcode them.
Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:
configdata.Incident_Field.forEach(function (k, i) {
this[k] = ticketarray[i];
}, ticketData);
Other people have explained why your code did not work. I am providing another solution using reduce.
const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];
let ticketData = configdata.reduce((result, value, index) => {
result[value] = ticketarray[index];
return result;
}, {});
console.log(ticketData);
Output:
{
assignee: "Tom",
shortDesc: "testDesc"
}
The below is not a valid structure in JavaScript:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
What you need is a JavaScript object. The best you can do is:
Make sure both the array lengths are same.
Associate the key and value by creating a new object.
Use Object.keys(obj).length to determine the length.
Start with the following code:
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];
if (configdata.length == ticketarray.length) {
var obj = {};
for (var i = 0; i < configdata.length; i++)
obj[configdata[i]] = ticketarray[i];
}
console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);
The above will give you an object of what you liked, a single variable with all the values:
{
"assignee": "Tom",
"shortDesc": "testDesc"
}
I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))
Very similar to this question:
Javascript: how to dynamically create nested objects using object names given by an array
Instead of calling
assign(obj, keyPath, value)
example of usage of the previously answer:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
That will output:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
The result would be:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
Edit:
Figured it out.
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}