how to make object's array from several array - javascript

For example,
I have a total of two arrangements.
The key array has keys.
The remaining arrays are multi arrays in one array like [[A], [B], [C], ...]
So how do we put objects in one array?
let key = [“name”, “age”, “country”];
let values = [["james", "23", "US"],["steve", "20", "UK"], ...]
** expect result **
result = [
{
"name": "james",
"age": 23,
"country": "US"
},
{
"name": "steve",
"age": 20,
"country": "UK"
},
...
]

Single line using array map and reduce functions:
values.map(v=>(key.reduce((acc, k, i) => ({...acc, [k]: v[i]}), {})));
(Note your original question contains non-ASCII quotation marks “” - you need to use " for valid JS syntax).

if you have data as name age and country with same keys so you can try below code it should work for you.
let values = [["james", "23", "US"],["steve", "20", "UK"], ...]
const result = [];
values.forEach(item => {
const [name, age, country] = item;
result.push({ name, age, country });
});
console.log(result)

I just asked your question to OpenAI JavaScript Codex and it returned this result.
/* let key = [“name”, “age”, “country”]; */
var key = ["name", "age", "country"];
/* let values = [["james", "23", "US"],["steve", "20", "UK"]] */
var values = [["james", "23", "US"],["steve", "20", "UK"]];
/* So how do we put objects in one array? */
var objects = [];
for (var i = 0; i < values.length; i++) {
var object = {};
for (var j = 0; j < key.length; j++) {
object[key[j]] = values[i][j];
}
objects.push(object);
}
I really don't know if it works or not, but I am curious to see what it does. You should try this.
Please forgive me if it doesn't work. Thanks

const objs = values.map(
(valSet) =>
Object.fromEntries(
valSet.map(
(val,i) => [val,keys[i]]
)
)
);
make entry arrays and then use this

Related

Data to be extracted from JSON like (JSONobj.name.fname) here (name.fname) is given in form of string by user, how to parse the query and get ans?

A text in JSON format is given in the form of a string, and Queries is given consisting of key of given JSON object in the form of a string.
For each query, value of that key is to be printed.
JSONtext = `{"Student":{"Name":"John","Age":"15"},"Class":"10"}`;
NoOfQueries=3;
queries=["Student.Name","Student.Age", "Class"];
ansShouldBe = John 15 10
queries[0] = ("Student.Name") ans should be calculated ans = myobj.Student.Name is "John",
similarly for 2nd is 15 & 3rd is 10
I have written just the beginning of the code, can someone help me to complete this?
function jsonfn(text,N,queries){
let myObj = JSON.parse(text);
for(let i=0; i<queries.length ; i++)
{
let query = queries[i]; //student.name
console.log(myObj.query) //this is giving undefined
// please complete this code
}
}
If I run myObj.Student.Nameit gives ans as "John" but how to do it dynamically if Student.Name is given in a string provided by user. How to parse Json object at run time? is there a way we can do it
The object can also be deeply nested like
{
"c": {
"mf": {
"he": "k"
}
},
"p": "q"
}
Same with the queries
["c.mf.he", "p"]
Please someone help me on this.
You can't use directly the array values in the object (like this: obj.array_values), they both have different types.
Try this one! It works fine.
function jsonfn(text, queries){
let myObj = JSON.parse(text);
for(let i = 0; i< queries.length ; i++)
{
let query = queries[i];
if (Array.isArray(query)) {
console.log(myObj[query[0]][query[1]]);
}
else {
console.log(myObj[query]);
}
}
}
let JSONtext = `{"Student":{"Name":"John","Age":15},"Class":10}`;
let queries=[["Student", "Name"], ["Student", "Age"], "Class"];
jsonfn(JSONtext, queries)
Thanks #siddharthRastogi I just changed your ans a bit, and got this!
let JSONtext = `{
"Student": {
"Name": "John",
"Age": "15"
},
"Class": "10",
"Address": {
"Country": {
"State": {
"City": {
"location": "12, abc road",
"pincode": "987654"
}
}
}
}
}`;
let queries=["Student.Name","Student.Age", "Class" , "Address.Country.State.City.location","Address.Country.State.City.pincode"];
queries = changeQueryArr(queries);
Added a function to changeQueryArr() to convert queries into dot splitted queries for deeply nested objects.
function changeQueryArr(queries)
{
let ans = []
for(let i=0;i<queries.length;i++)
{
let str = queries[i];
ans.push(str.split("."));
}
return ans;
}
now queries would look like
// queries=[["Student", "Name"], ["Student", "Age"], "Class",["Address","Country","State","City","location"],["Address","Country","State","City","pincode"]];
function jsonfn(text, queries){
let myObj = JSON.parse(text);
for(let i = 0; i< queries.length ; i++)
{
let query = queries[i];
if (Array.isArray(query)) {
console.log( query.reduce((prev, curr) => prev?.[curr], myObj))
}
else {
console.log(myObj[query]);
}
}
}
jsonfn(JSONtext, queries)
// Ans :-
// John
// 15
// 10
// 12, abc road
// 987654

How do i add a key value pair to an asociative array in javascript

let finaloutput = {};
$.each( arr, function(index,key) {
let outarray = [];
// var id sourced from another function
outarray.push(id,index,key);
//??finaloutput[id].push(outarray);
}
In the above code i am trying to store an object similar to below.
Each time the loop grabs the same id it appends the array in the finaloutput object
eg
id:index:key
1st loop where id = 7 index=param 1 key=val1
{"7":[{param1:val1}]}
2nd .. id = 7 index=param 2 key=val2
{"7":[{param1:val1,param2:val2}]}
3rd ... id = 8 index=param 1 key=val1
{"7":[{param1:val1,param2:val2}],"8":[{param1:val1}]}
How do i achieve this
I tried to generated similar output using sample data:
`let indx = ["param1", "param2", "param3", "param4", "param5"]
let key = ["k1", "k2", "k3", "k4", "k5"]
let id = ["1", "2", "3", "4", "5"]
let resultObj = {}
for (let i = 0; i < 5; i++) {
if (resultObj[id]) {
let temp=Object.assign({}, {[indx[i]]:key[i]}, ...resultObj[id[i]])
resultObj[id[i]] = [temp];
}
else{
let ob=[{[indx[i]]:key[i]}]
resultObj[id[i]]=ob
}
}
console.log(resultObj)`
In your case you can do something like :
let finaloutput = {};
$.each(arr, function (index, key) {
if (finaloutput[id]) {
let temp = Object.assign({}, { [index]: key }, ...finaloutput[id])
finaloutput[id] = [temp];
}
else {
let temp2 = [{ [index]: key }]
finaloutput[id] = temp2
}
}
Note Please refer to my example to get better understanding incase I was not able to exactly formulate answer of your code or it gives error
You have an object finaloutput. So your goal can be divided into smaller pieces:
just create a key in object
assign an array to the above key
push desired values into array
So the code should look like this:
let finaloutput = {};
$.each( arr, function(index,key) {
finaloutput[key] = [];
let outarray = [];
// var id sourced from another function
finaloutput[key].push({id:key});
}
Or it can be done using reduce() method. Let me show an example::
const array = ["one", "two", "three", "one", "one", "two", "two", "three", "four", "five"];
const result = array.reduce((a, c) => {
a[c]=a[c] || [];
a[c].push({yourKey: c});
return a;
}, {})
console.log(result);

Count and loop through JSON object of arrays

I get issues when I want to loop through a JSON array of objects.
Issues such as:
It only counts two (I assume because of they Object.keys) and I have two keys.
Loops with only one value
My code:
var codes = require('./nl.json');
for (var i = 0, l = Object.keys(codes).length; i <= l; i++) {
console.log(l) ;
var areaCodeTest = codes.netherlands[i].areaCode;
var areaNameTest = codes.netherlands[i].areaName;
it("Search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
browser.sleep(1000);
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
My Json (Short example):
{
"netherlands": [
{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
I have looked at answers such as :
Size of Object and
Length of Json
I have tried:
(var i = 0, l = Object.keys(codes).length; i <= l; i++)
(var i = 0, l = Object.keys(codes.netherlands[0]).length; i <= l; i++)
for (var i = 0, l = codes.netherlands.length; i <= l; i++) // uses last areaCode in json file and only loop with that number. It does not start from top.
Image:
some of my outputs
Expected:
What I want is to count amount of ofjects in JSON (Not the key/values)
Loop through all data and assign them to var areaCodeTest = codes.netherlands[i].areaCode; and var areaNameTest = codes.netherlands[i].areaName;
I got it to work by using the following:
var codes = require('./nl.json');
codes.forEach((item) => {
var areaCodeTest = item.areaCode;
var areaNameTest = item.areaName;
it("and search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
I am not a 100% what the => means near the foreach but I am currently researching why my code works. If you know please post a comment so that other developers also learn.
This let me think of the meme "not sure why code does not work / Not sure why code works"
You need to access the actual key in your loop in order to access codes[key]
Simplified version of your for() loop with stored variable for the object keys or using for in loop
const keys = Object.keys(codes)
for (let i = 0; i < keys.length; i++) {
// current object key and value of that property in main object
const key = keys[i], arr = codes[key];
console.log(`key = ${key}, length= ${arr.length}`)
// do another loop here for `arr` if needed
}
// OR using `for in`
for (let key in codes) {
console.log(`key = ${key}, length= ${codes[key].length}`)
}
<script>
const codes = {
"netherlands": [{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
</script>
Try this I give you a sample
const object1 = {
a: 'somestring',
b: 42,
c: false
};
var length = (Object.keys(object1).length);
Please Refer this Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Nested JSON string to dictionary with object to be used as key

I am loading a nested JSON query and I am trying to create a dictionary that will have a specific object as a key. Sp, in my case, the key will be the country and then each dictionary value will have the date and the number. I have made a progress but I am stuck at the final function. My snippet prints all the steps in the HTML part.
So, I am actually trying to convert this:
2018-05-01,Italy,25,2018-04-01,Italy,37,2018-05-01,France,30,2018-04-01,France,90
to this:
{"Italy":[{"Date":"2018-04-01","num":37},{"Date":"2018-05-01","num":25}],"France":[{"Date":"2018-04-01","num":90},{"Date":"2018-05-01","num":30}]}
which will then be converted to:
[
{
"Value": "Italy",
"num": 37,
"num2": 25
},
{
"Value": "France",
"num": 90,
"num2": 30
}
]
where num will have the number of the first date and num2 will have the number of the second date.
Also, feel free to provide a completely different solution if you believe that my steps are too many.
var json_data = {"headers":["Month","Country","Number"],"rows":[["2018-05-01","Italy",25],["2018-04-01","Italy",37],["2018-05-01","France",30],["2018-04-01","France",90]
]};
var dataRows = json_data.rows;
document.getElementById("yellow").innerHTML = dataRows;
//Returns unique values of a specific object of a JSON string
uniqueValues = (data,objectNum) => {
var uniqueValues = [];
data.forEach(function(item) {
var value = item[objectNum];
if (uniqueValues.indexOf(value) !== -1)
return false;
uniqueValues.push(value);
});
return uniqueValues;
}
var uniqueCountries = uniqueValues(dataRows,1);
document.getElementById("green").innerHTML = uniqueCountries;
var uniqueDates = uniqueValues(dataRows,0);
document.getElementById("blue").innerHTML = uniqueDates;
//Create dictionary function (transformed JSON)
createDict = (data,objectNum) => {
var dict =[];
var num = 0;
var num2 = 0;
for (i = 0; i < dataRows.length; i++)
{
var object = {"Date": dataRows[i][0].slice(0,10), "Value": dataRows[i][1], "num": dataRows[i][2]};
dict.push(object);
}
return dict;
}
var dictData = createDict(dataRows,2);
document.getElementById("orange").innerHTML = JSON.stringify(dictData);
//Function that will return the final output
function test (){
var sumMetric = {};
dictData.forEach(function(d) {
uniqueCountries.forEach(function(country) {
console.log(d.Date);
//d.num = +d.num;
sumMetric[country] = [];
uniqueDates.forEach(function(element) {
sumMetric[country].push({Date: d.Date, num: d.num});
});
});
});
document.getElementById("red").innerHTML =JSON.stringify(sumMetric);
return sumMetric;
}
test();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
<h4>Original JSON</h4>
<div style="background:yellow;" id="yellow"></div>
<h4>Unique Countries</h4>
<div style="background:green; color:white" id="green"></div>
<h4>Unique Dates</h4>
<div style="background:blue; color:white" id="blue"></div>
<h4>Dictionary Creation</h4>
<div style="background:orange;" id="orange"></div>
<h4>Wrong Output</h4>
<div style="background:red;" id="red"></div>
<h4>Expected Output</h4>
<div style="background:purple; color:white" id="purple">{"Italy":[{"Date":"2018-04-01","num":37},{"Date":"2018-05-01","num":25}],"France":[{"Date":"2018-04-01","num":90},{"Date":"2018-05-01","num":30}]}</div>
<h4>Final Output that I need</h4>
<div style="background:grey; color:black" id="purple">[
{
"Value": "Italy",
"num": 37,
"num2": 25
},
{
"Value": "France",
"num": 90,
"num2": 30
}
]<div>
Assuming that the array of arrays in your snippet is the correct input dataset to start with (rather than the string posted at the beginning of your question)...
If the original array is guaranteed to only have 2 sub-arrays for each country, then you can use reduce to group it into an object by country key and then compare the array pairs in the grouped object to produce the desired results. For example:
const data = [["2018-05-01", "Italy", 25], ["2018-04-01", "Italy", 37], ["2018-05-01", "France", 30], ["2018-04-01", "France", 90]];
const groups = data.reduce((acc, arr) => {
if (acc.hasOwnProperty(arr[1])) {
acc[arr[1]].push(arr);
} else {
acc[arr[1]] = [arr];
}
return acc;
}, {});
let results = [];
for (const g in groups) {
const obj = { value: g };
const a = groups[g][0];
const b = groups[g][1];
if (a[0] <= b[0]) {
obj.num = a[2];
obj.num2 = b[2];
} else {
obj.num = b[2];
obj.num2 = a[2];
}
results.push(obj);
}
console.log(results);
If the original array is not guaranteed to have only 2 sub-arrays for each country, then you would have to modify the for...in loop above to loop through and compare multiple country arrays (rather than just comparing a single pair) and update the result objects as needed.

Remove the object or item which I have in the json string format from javascript array named data?

var item = {"mtyp":2,"mtr":3,"qnt":51,"unt":"pint","nts":"cvbbcv"}
var data = [{"mtyp":"2","mtr":"2","qnt":"54","unt":"ml","nts":"ngvjn"},{"mtyp":"2","mtr":"3","qnt":"51","unt":"pint","nts":"cvbbcv"}]
output should be:
var data = [{"mtyp":"2","mtr":"2","qnt":"54","unt":"ml","nts":"ngvjn"}]
You can use below script that I have written to meet your requirement.
I am assuming that your JSON object will have similar key names at both end, if not then let me know I will update the script for you.
Your desired result will be available in resultdata.
<script type="text/javascript">
var item = { "mtyp": 2, "mtr": 3, "qnt": 51, "unt": "pint", "nts": "cvbbcv" }
var data = [{ "mtyp": "2", "mtr": "2", "qnt": "54", "unt": "ml", "nts": "ngvjn" }, { "mtyp": "2", "mtr": "3", "qnt": "51", "unt": "pint", "nts": "cvbbcv" }]
// Holds the result data.
var resultdata = [{}];
// Remove initialized result set.
resultdata.pop();
// Variable to hold comparison value.
var hasMatch = false;
// Loop through data values.
for (var index = 0; index < data.length; ++index) {
// Fetch current item.
var individualData = data[index];
// Compare item values with individual data values.
if (item.mtyp == individualData.mtyp &&
item.mtr == individualData.mtr &&
item.qnt == individualData.qnt &&
item.unt == individualData.unt &&
item.nts == individualData.nts) {
hasMatch = true;
}
else {
hasMatch = false;
}
// If then is no match then add to the result.
// ResultData will hold all the values that are not present in item.
if (!hasMatch)
{ resultdata.push(individualData); }
}
</script>
While the question is quite unclear, if you like to get a new array or an in situ (in place) solution, and despite some values does not match type wise, like
qnt: 51
and
qnt: "51"
I suggest to use a combination of Array#filter for the array itself and Object.keys with Array#every for checking all properties and get all items who not match.
var item = { mtyp: 2, mtr: 3, qnt: 51, unt: "pint", nts: "cvbbcv" },
data = [{ mtyp: "2", mtr: "2", qnt: "54", unt: "ml", nts: "ngvjn" }, { mtyp: "2", mtr: "3", qnt: "51", unt: "pint", nts: "cvbbcv" }];
data = data.filter(function (a) {
return !Object.keys(item).every(function (k) {
return a[k] == item[k];
});
});
console.log(data);

Categories

Resources