adding json key names to a json values and changing key names - javascript

I have a json string that is in the format:
[
{
clientIDs:
"WELL #6",
analyteIDs:
[
"7440-62-2",
"7440-28-0"
]
}
]
I need to convert this to:
[
{
header:
"WELL #6",
items:
[
header: "7440-62-2",
header: "7440-28-0"
]
}
]
The values without a key name are throwing me off.

Unfortunately js cannot store a key value arrays, instead you have to use an object storing key and value. So the closes result you can achieve is following:
[
{
header:
"WELL #6",
items:
[
{ header: "7440-62-2" },
{ header: "7440-28-0" }
]
}
]
For that your steps will be following:
Assuming you have an array of objects.
Assuming the keys you want to change are static and will always exist in the objects
const myObjects = [
{
clientIDs:
"WELL #6",
analyteIDs:
[
"7440-62-2",
"7440-28-0"
]
}
]
myObjects.map((myObj) => {
myObj['header'] = myObj.clientIDs;
myObj['items'] = myObj.analyteIDs.map((item) => {
return { header: item }
});
// Keep in mind, if keys are dynamic and does not exist in some objects then this will fail
delete myObj['clientIDs'];
delete myObj['analyteIDs'];
});
console.log(myObjects);

Related

find and update property of nested object with lodash

I have been scanning through stackoverflow topics and couldn't find answer to the problem i am having.
What i need to do is to find object inside nested (2 depths) array by some of the values and then update other of its values. I managed to put together the finding and also setting seems to work, the problem is that lodash does return main object and it updates main object, not the nested one i actually need.
lets take this structure:
var data = [
{
name: 'I',
status: "0",
categories: [
{
name: 'I1',
status: "0",
specifics: [
{
name: "I1a",
status: "0",
}
]
}
]
}
];
i need to find object inside specifics by its name and then update its status.
so lets try simple find first:
var find = _.find(data, { categories: [ { specifics: [ { name: "I1a" } ] } ]});
this is working but it returns the object with name: I so first main one.
so then if i try to update with this:
var set = _.set(_.find(data, { categories: [ { specifics: [ { name: "I1a" } ] } ]}), 'status', "1");
It also does work but it updates status of I instead of what i was looking for which is I1a.
Is there a way to make finding and therefore setting to return / work on actually queried object ?
var data = [
{
name: 'I',
status: "0",
categories: [
{
name: 'I1',
status: "0",
specifics: [
{
name: "I1a",
status: "0",
}
]
}
]
}
];
var find = _.find(data, { categories: [ { specifics: [ { name: "I1a" } ] } ]})
console.log('find', find);
var set = _.set(_.find(data, { categories: [ { specifics: [ { name: "I1a" } ] } ]}), 'status', "1");
console.log('set', set);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Finding nested object data using basic JavaScript

I want to loop through 600+ array items in an object and find one particular item based on certain criteria. The array in the object is called "operations" and its items are arrays themselves.
My goal is to get the index of operation's array item which has the deeply nested string "Go".
In the sample below this would be the first element. My problem is that I can check if an array element contains "call" and "draw" but I don't know how to test for the nested dictionary "foobar". I only have basic JavaScript available, no special libraries.
let json = {
"head": {},
"operations": [
[
"call",
"w40",
"draw",
{
"parent": "w39",
"style": [
"PUSH"
],
"index": 0,
"text": "Modify"
}
],
[
"call",
"w83.gc",
"draw",
{
"foobar": [
["beginPath"],
[
"rect",
0,
0,
245,
80
],
["fill"],
[
"fillText",
"Go",
123,
24
],
[
"drawImage",
"rwt-resources/c8af.png",
]
]
}
],
[
"create",
"w39",
"rwt.widgets.Menu",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
],
[
"call",
"w39",
"draw",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
]
]
};
let index = "";
let operationList = json.operations;
for (i = 0; i < operationList.length; i++) {
if (operationList[i].includes('call') && operationList[i].includes('draw')) //missing another check if the dictionary "foobar" exists in this element )
{
index = i;
}
}
document.write(index)
I'll preface by saying that this data structure is going to be tough to manage in general. I would suggest a scheme for where an operation is an object with well defined properties, rather than just an "array of stuff".
That said, you can use recursion to search the array.
If any value in the array is another array, continue with the next level of recursion
If any value is an object, search its values
const isPlainObject = require('is-plain-object');
const containsTerm = (value, term) => {
// if value is an object, search its values
if (isPlainObject(value)) {
value = Object.values(value);
}
// if value is an array, search within it
if (Array.isArray(value)) {
return value.find((element) => {
return containsTerm(element, term);
});
}
// otherwise, value is a primitive, so check if it matches
return value === term;
};
const index = object.operations.findIndex((operation) => {
return containsTerm(operation, 'Go');
});

How to Iterate Over Array and Stringify a Property

I am trying to accumulate a property of an array and write save it back to the array as a string to later be parsed with JSON.parse.
In the initial data set the items property is an array.
I would like to restructure the data such that items is a string of the objects.
Given something like:
[{
{
"n":"1",
"items": [0: "{"id":"id1","desc":"description1"}",
1: "{"id":"id2","desc":"description2"}"
2: "{"id":"id3","desc":"description3"}"]
},
{
"n":"2",
"items": [0: "{"id":"id4","desc":"description4"}",
1: "{"id":"id5","desc":"description5"}"
2: "{"id":"id6","desc":"description6"}"]
}
}]
Convert to:
[{
{
"n":"1",
"items": "[{"id":"id1","desc":"description1"}","{"id":"id2","desc":"description2"}","{"id":"id3","desc":"description3"}]"
},
{
"n":"2",
"items": "[{"id":"id4","desc":"description4"}","{"id":"id5","desc":"description5"}", "{"id":"id6","desc":"description6"}]"
}
}]
I had to clean up your data, so I will go with the assumption that the data structure I set below is what you actually meant.
const data = [
{
"n":"1",
"items": [
{"id":"id1","desc":"description1"},
{"id":"id2","desc":"description2"},
{"id":"id3","desc":"description3"}
]
},
{
"n":"2",
"items": [
{"id":"id4","desc":"description4"},
{"id":"id5","desc":"description5"},
{"id":"id6","desc":"description6"}
]
}
];
const newData = data.map(val => {
return Object.assign({}, val, {
items: JSON.stringify(val.items)
});
});
console.log(newData);
arr.map(({ items, ...rest }) => ({ items: JSON.stringify(items), ...rest }));

java script 2D array find unique array combinations

I need to know the best way to get following results
courseFrequency : [
{
'courses': [
'a.i'
],
'count' : 1
},
{
'courses': [
'robotics'
],
'count' : 2
},
{
'courses': [
'software engineering', 'a.i'
],
'count' : 2
},
{
'courses': [
'software engineering', 'a.i','robotics'
],
'count' : 1
}
]
from following json data.
arr = [
{
'courses': [
'a.i'
]
},
{
'courses': [
'robotics'
]
},
{
'courses': [
'software engineering', 'a.i'
]
},
{
'courses': [
'robotics'
]
},
{
'courses': [
'software engineering', 'a.i'
],
'courses': [
'software engineering', 'a.i','robotics'
]
}];
Basically i need to find out the unique courses and their frequency. What is the most optimal way to do that ?
const hash = {}, result = [];
for(const {courses} of arr){
const k = courses.join("$");
if(hash[k]){
hash[k].count++;
} else {
result.push(hash[k] = { courses, count : 1 });
}
}
Simply use a hashmap to find duplicates. As arrays are compared by reference, we need to join it to a string for referencing ( note that this will fail if a coursename contains the joining symbol ($))
There both of them are best for area relates to them.These concepts are heaving their own property and methods to accomplish a certain task like JSON used for data transfer and cross browsing aspect as the common type data value.Arrays are really good at storing ordered lists and ordering things while the cost of removing/splicing elements is a bit higher.
JSON is a representation of the data structure, it's not an object or an array.
JSON can be used to send data from the server to the browser, for example, because it is easy for JavaScript to parse into a normal JavaScript data structure.for doing an action on JSON data you need to convert it into an object which is also seamed some property like ARRAY.
Arrays are really good at storing ordered lists and ordering things while the cost of removing/splicing elements is a bit higher.
Relative link
Relative link

Insert array of objects to database

I have the following array containing objects, And there are arrays in the objects too.
let array = [
{
"data": {
"Game": {
"Game_number": [
"4",
"6",
"8"
],
"Game_name": [
"Name_1",
"Name_2",
"name_3"
]
},
"AA": {
"AA_count": [
"30"
],
"AA_name": [
"Umbrella"
]
},
}
}
]
Now i have to put them in database, Each have a column against.
But the issue is that the above data is not constant, So i cannot put them via their indexes. if the data is missing for a column than that's fine it will go empty
I tried via for each but that is inserting the last element of the array.
array.data.forEach((item) => {
const Games = Parse.Object.extend('Games');
const query = new Games();
item.data.Game.Game_number.forEach((number) => {
query.set('game_number', number);
}, this);
item.data.Game.Game_name.forEach((name) => {
query.set('game_name', name);
}, this);
query.save();
}, this);
What will be a flexible way to handle it ?

Categories