Simple JavaScript Convert JSON format - javascript

I have a json format and want to convert
Here are my script. I had tried but cannot get the correct results. Please give some advice, thanks and appreciate.
function groupBy() {
var list = [{
"id": "009",
"Nm": "Model 1",
"pid": "adidas"
},
{
"id": "007",
"Nm": "Model 1",
"pid": "adidas"
},
{
"id": "006",
"Nm": "Model 1",
"pid": "adidas"
},
{
"id": "pm1",
"Nm": "Model 1",
"pid": "puma"
},
{
"id": "003",
"Nm": "Model 1",
"pid": "adidas"
},
{
"id": "pm5",
"Nm": "Model 1",
"pid": "puma"
},
{
"id": "aj1",
"Nm": "Model 1",
"pid": "nike"
},
{
"id": "aj2",
"Nm": "Model 1",
"pid": "nike"
}
];
var output = [];
for (var i = 0; i < list.length; i++) {
if (list[i].pid != undefined) {
output.push(list[i]);
}
}
console.log(output);
}
groupBy();

One option is to reduce into an object indexed by pids, whose values are arrays. On each iteration, create the array at the appropriate property if it doesn't exist, and then push to that array:
var list = [
{"id":"009","Nm":"Model 1","pid":"adidas"},
{"id":"007","Nm":"Model 1","pid":"adidas"},
{"id":"006","Nm":"Model 1","pid":"adidas"},
{"id":"pm1","Nm":"Model 1","pid":"puma"},
{"id":"003","Nm":"Model 1","pid":"adidas"},
{"id":"pm5","Nm":"Model 1","pid":"puma"},
{"id":"aj1","Nm":"Model 1","pid":"nike"},
{"id":"aj2","Nm":"Model 1","pid":"nike"}
];
console.log(
list.reduce((a, item) => {
const { pid } = item;
if (!a[pid]) a[pid] = [];
a[pid].push(item);
return a;
}, {})
);

You're pretty close there. But [] is to initialize an array instead of an object in javascript. In JS, it's {}.
Following is one of many ways you can accomplish this.
function groupBy() {
var list = [
{"id":"009","Nm":"Model 1","pid":"adidas"},
{"id":"007","Nm":"Model 1","pid":"adidas"},
{"id":"006","Nm":"Model 1","pid":"adidas"},
{"id":"pm1","Nm":"Model 1","pid":"puma"},
{"id":"003","Nm":"Model 1","pid":"adidas"},
{"id":"pm5","Nm":"Model 1","pid":"puma"},
{"id":"aj1","Nm":"Model 1","pid":"nike"},
{"id":"aj2","Nm":"Model 1","pid":"nike"}
];
// Initialize output as an object
var output = {};
for (var i = 0; i < list.length; i++){
// 'objectKey' is where you group the list item by its 'pid'
var objectKey = list[i].pid;
// If there's a 'pid' in the list item, but 'output' is not an array yet, then..
if (objectKey && !output.hasOwnProperty(objectKey)){
// Initialize output.group to be an array
output[ objectKey ] = [];
}
// Then finally, store the list into output's group that we created above.
output[ objectKey ].push( list[i] );
}
console.log(output);
}
groupBy();

Use this method for your any group by
const groupBy = function(arr, prop) {
return arr.reduce(function(groups, item) {
const val = item[prop]
groups[val] = groups[val] || []
groups[val].push(item)
return groups
}, {})
}
const list = [
{"id":"009","Nm":"Model 1","pid":"adidas"},
{"id":"007","Nm":"Model 1","pid":"adidas"},
{"id":"006","Nm":"Model 1","pid":"adidas"},
{"id":"pm1","Nm":"Model 1","pid":"puma"},
{"id":"003","Nm":"Model 1","pid":"adidas"},
{"id":"pm5","Nm":"Model 1","pid":"puma"},
{"id":"aj1","Nm":"Model 1","pid":"nike"},
{"id":"aj2","Nm":"Model 1","pid":"nike"}
];
const groupOutput = groupBy(list, 'pid');
You pass your key as second argument into groupBy for group by.

Related

Postman JSON parse response body arrays inside arrays

I have this JSON Response from API call
[
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
I am using this code to get the id of the service "Deliver"
var data = JSON.parse(responseBody);
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
}
}
The questions are:
How can I get value from array "options", I need to get the "id":
63775 and store as "item_id" and the "name":"Item" as "item_name" postman variables.
Then I need to select the "options" nested in record
"Item" and select the option "name": "Toothbrush" and store in postman
variable "svc_optn_optn_name" and it's "id" stored in
"svc_optn_optn_id"
Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj) which takes object as parameter which is the value of data[count], gathers necessary info in other object postmanObj and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.
This is the solution
var data = JSON.parse(responseBody);
variable named as data
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
var job1_name = data[count].options[0].name;
postman.setEnvironmentVariable("item_name", job1_name);
var job2_id = data[count].options[0].id;
postman.setEnvironmentVariable("item_id", job2_id);
var job3_id = data[count].options[0].options[1].id;
postman.setEnvironmentVariable("svc_optn_optn_id", job3_id);
var job4_name = data[count].options[0].options[1].name;
postman.setEnvironmentVariable("svc_optn_optn_name", job4_name);
}
const data = JSON.parse(responseBody);
data.forEach(item => {
console.log(item.id); // deliver object id.
item.options.forEach(option => {
console.log(`Option Id ${option.id}`); // option id
postman.setEnvironmentVariable("service_id", option.id);
option.options(optionItem => {
if(optionItem.name == 'Toothbrush'){
postman.setEnvironmentVariable("svc_optn_optn_name", optionItem.name);
postman.setEnvironmentVariable("svc_optn_optn_id", optionItem.id);
}
});
});
});

Remove a particular name inside an array [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
{
"list": [{
"name": "car",
"status": "Good",
"time": "2018-11-02T03:26:34.350Z"
},
{
"name": "Truck",
"status": "Ok",
"time": "2018-11-02T03:27:23.038Z"
},
{
"name": "Bike",
"status": "NEW",
"time": "2018-11-02T13:08:49.175Z"
}
]
}
How do I remove just the car info from the array.
To achieve expected result, use filter option to filter out car related values
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
result.list.push(obj.list.filter(v => v.name !=='car'))
console.log(result)
codepen - https://codepen.io/nagasai/pen/MzmMQp
Option 2: without using filter as requested by OP
Use simple for loop to achieve same result
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
for(let i =0; i< obj.list.length; i++){
if(obj.list[i].name !== 'car' ){
result.list.push(obj.list[i])
}
}
console.log(result)
const obj = JSON.parse(jsonString);
let yourArray = obj.list;
let filteredArray = yourArray.filter(elem => elem.name !== "car");

Build array from another array if some key are identical using JavaScript

I have an array of data. Some of the key in the array are same. I would like to create a new array based on the key and add the other data.
This is my array
var myObjOne = [
{
"name":"John",
"id":1,
"car":"maruti"
},
{
"name":"John",
"id":2,
"car":"wolks"
},
{
"name":"John",
"id":3,
"car":"bmw"
},
{
"name":"Peter",
"id":4,
"car":"alto"
},
{
"name":"Peter",
"id":5,
"car":"swift"
}
];
I would like to convert the array in to the below format.
var myObj = [
{
"name":"John",
"items": [
{ "id":1, "car":"maruti" },
{ "id":2, "car":"wolks" },
{ "id":3, "car":"bmw" }
]},
{
"name":"Peter",
"items": [
{ "id":4, "car":"alto" },
{ "id":5, "car":"swift" },
]
}
];
I am working on a node environment.
You can create an object using Array#reduce first which maps name with items, and then create the final array by looping over the intermediate map using a for...of loop:
var source = [{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}];
const map = source.reduce((acc, {name, ...obj}) => {
if (!acc[name]) {
acc[name] = [];
}
acc[name].push(obj);
return acc;
}, {});
const result = [];
for (let[name, items] of Object.entries(map)) {
result.push({name, items});
}
console.log(result);
Array.reduce is at rescue.This method accepts an accumulator and current
item. Check in the accumulator if there exist an object where the value of name property is John or Peter
var myObjOne = [{
"name": "John",
"id": 1,
"car": "maruti"
},
{
"name": "John",
"id": 2,
"car": "wolks"
},
{
"name": "John",
"id": 3,
"car": "bmw"
},
{
"name": "Peter",
"id": 4,
"car": "alto"
},
{
"name": "Peter",
"id": 5,
"car": "swift"
}
];
var newObj = myObjOne.reduce(function(acc, curr, currIndex) {
// using findIndex to check if there exist an object
// where the value of the name property is John, Peter
// if it exist it will return the index else it will return -1
let ifNameExist = acc.findIndex(function(item) {
return item.name === curr.name;
})
// if -1 then create a object with name and item property and push
// it to the accumulator
if (ifNameExist === -1) {
let nameObj = {};
nameObj.name = curr.name;
nameObj.items = [];
nameObj.items.push({
id: curr.id,
car: curr.car
})
acc.push(nameObj)
} else {
// if such an object already exist then just update the item array
acc[ifNameExist].items.push({
id: curr.id,
car: curr.car
})
}
return acc;
}, []);
console.log(newObj)
Use .reduce to group by name, and use .find inside the reducer to find if the matching name has already been added:
const input=[{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}]
const output = input.reduce((a, { name, ...item }) => {
const foundNameObj = a.find(nameObj => nameObj.name === name);
if (foundNameObj) foundNameObj.items.push(item);
else a.push({ name, items: [item] });
return a;
}, []);
console.log(output);

How to add a new key to multiple indices of an array of objects?

I've got an array of three people. I want to add a new key to multiple objects at once based on an array of indices. Clearly my attempt at using multiple indices doesn't work but I can't seem to find the correct approach.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
}
];
array[0,1].title = "Manager";
array[2].title = "Staff";
console.log(array);
Which returns this:
[
{
"name": "Tom",
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
But I'd like it to return this.
[
{
"name": "Tom",
"title": "Manager"
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
You cannot use multiple keys by using any separator in arrays.
Wrong: array[x, y]
Correct: array[x] and array[y]
In your case, it will be array[0].title = array[1].title = "manager";
1st method::
array[0].title = "Manager";
array[1].title = "Manager";
array[2].title = "Staff";
array[0,1] will not work.
2nd method::
for(var i=0;i<array.length;i++) {
var msg = "Manager";
if(i===2) {
msg = "Staff"
}
array[i].title = msg
}
You can use a helper function like this
function setMultiple(array, key, indexes, value)
{
for(i in array.length)
{
if(indexes.indexOf(i)>=0){
array[i][key] = value;
}
}
}
And then
setMultiple(array, "title", [0,1], "Manager");
Try this: `
for (var i=0; var<= array.length; i++){
array[i].title = "manager";
}`
Or you can change it around so var is less than or equal to any n range of keys in the index.
EDIT: instead make var <= 1. The point is to make for loops for the range of indices you want to change the title to.
Assuming that you have a bigger set of array objects.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
},
.
.
.
];
Create an object for the new keys you want to add like so:
let newKeys = {
'Manager': [0,2],
'Staff': [1]
}
Now you can add more such titles here with the required indexes.
with that, you can do something like:
function addCustomProperty(array, newKeys, newProp) {
for (let key in newKeys) {
array.forEach((el, index) => {
if (key.indexOf(index) > -1) { // if the array corresponding to
el[newProp] = key // the key has the current array object
} // index, then add the key to the
}) // object.
}
return array
}
let someVar = addCustomProperty(array, newKeys, 'title')

How can I remove the parent keys from a javascript Object?

I currently have this Object:
schoolsObject = [{
"college_1":
{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
I want to remove the top level keys ie. college_1, college_2 and 'flatten' the object out like this, so I have no 'top level' keys:
flatSchoolsObject =
[{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}];
Here is my latest attempt, I've made a lot of different try's but have not been documenting them:
// schoolIDs = Object.keys(schoolsObject);
var schools = {};
for(var i=0; i<Object.keys(schoolsObject).length; i++){
for (var property in schoolsObject) {
if (schoolsObject.hasOwnProperty(property)) {
schools[i] = {
'id': schoolsObject[property]['id'],
'name' : schoolsObject[property]['name'],
'location': schoolsObject[property]['location'],
};
}
}
}
console.log(schools)
Obviously this one is not what I'm after as it leaves me with Object {0: Object, 1: Object}.
Is what I want to do here possible or am I looking at it the wrong way?
Given Object:
schoolsObject = [{
"college_1":{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
Solution:
Object.values(schoolsObject[0]);
Result:
[{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}]
(Codewise) simplest solution could be using a combination of Object.keys() and Array.map():
flatSchoolsObject = Object.keys( schoolsObject[0] )
.map( ( key ) => schoolsObject[0][ key ] );
If the schoolsObject array has more entries, the code would have to be slightly adjusted:
let step1 = schoolsObject.map( ( el ) => {
return Object.keys( schoolsObject[0] )
.map( ( key ) => schoolsObject[0][ key ] );
})
flatSchoolsObject = [].concat.apply( [], step1 );
(the step1 variable is just introduced for readability reasons.)
You need to concat the result of extracting values from each item in schoolObject
flatSchoolsObject = [].concat.call(
schoolsObject.map(function(item) {
return Object.keys(item).map(function(key) {
return item[key];
})
})
)
or using Array.prototype.reduce
flatSchoolsObject = schoolsObject.reduce(function(acc, item) {
return acc.concat(Object.keys(item).map(function(key){
return item[key]
})
}, [])
You can use Array#map on the result of Object.keys to do it. Since you have just a single object in the array, we do it like this:
schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
return schoolsObject[0][key];
});
Live example:
var schoolsObject = [
{
"college_1": {
"id": "college_1",
"location": "Victoria",
"name": "College One"
},
"college_2": {
"id": "college_2",
"location": "Tasmania",
"name": "College Two"
}
}];
schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
return schoolsObject[0][key];
});
console.log(schoolsObject);
With ES2015+ you could use an arrow function to make that shorter:
schoolsObject = Object.keys(schoolsObject[0]).map(key => schoolsObject[0][key]);
// Code goes here
var schoolsObject = [{
"college_1":
{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
var result = Object.keys(schoolsObject[0]).map(function(key){
return schoolsObject[0][key];
})
console.log(result);
other version
var schoolsObject = [{
"college_1": {
"id": "college_1",
"location": "Victoria",
"name": "College One"
},
"college_2": {
"id": "college_2",
"location": "Tasmania",
"name": "College Two"
}
}];
var result = [];
for (var property in schoolsObject[0]) {
if (schoolsObject[0].hasOwnProperty(property)) {
result.push(schoolsObject[0][property]);
}
}
console.log(result);

Categories