I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});
Related
I have two arrays:
dataArray1 = [{
"id":1
"addressDetails": {55:1,56:20}
},
{
"id":2
"addressDetails": {55:30,56:10}
}
]
Above array contains addressDetails as object.
dataArray2= [{
"id":1
"addressDetails": [
{
"addressId": "55",
"city":"london",
"code":1
},
{
"addressId": "56",
"city":"paris",
"code":1
}
]
},
{
"id":2
"addressDetails": [
{
"addressId": "55",
"city":"london",
"code":0
},
{
"addressId": "56",
"city":"paris",
"code":0
}
]
}
]
This second array contains arrayDetails as array.
In both the arrays, id and addressId will be same. On the basis of both these id's I need to replace addressDetails object in dataArray1 by addressDetails array of dataArray2. In this replacement, I need to change value of "code" property of addressDetails array with the right hand side value(value on right side in addressDetailObject) for that particular id and addressId. For example, for Id "1" and addressId "55", in addressDetails object - "addressDetails": {55:1,56:10} value is "1", so I need to change value of "code" property in addressDetailsArrays with 1 and copy rest attritubtes as it is. How can I do that?
For this you can run
let result = array1.map((item) => {
//code to change item here
//find address value of array2 based on id and addressId
//replace the code with the address.code details you found above
});
What we are doing here is iterating over items of array1 and returning an updated value for each item.
I have an array like this:
[
{
"id": 10002,
"flag": false,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10001,
"flag": true,
"list": [
"10002",
"10003"
]
},
{
"id": 10003,
"flag": false,
"list": [
"ccc",
"ddd"
]
}
]
i tried this
initially i have "10001" value so iterate this array to take "list" array if flag==true then stored into newarray. but its not working.
I want it to be like this: [ "aaa", "bbb", "ccc", "ddd" ].
If i understand correctly this is what you want:
const someArray = [
{
"id": 10001,
"list": [
"10002",
"10003"
]
},
{
"id": 10002,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10003,
"list": [
"ccc",
"ddd"
]
}
];
const [head,...rest] = someArray;
const result = head.list.reduce((acc,currentId)=>acc.concat(rest.find(({id})=> id === parseInt(currentId)).list),[]);
Here is a jsFiddle https://jsfiddle.net/sudakatux/9hju85mt/22/
Explanation:
take the head and splitted from the rest since the head contains the ids.
using the head as a dictionary find each list for each id in the head and concatenate
note the id must be in the subsequent list else it will fail with undefined. if you want to account for this error you can set a defualt empty object with a list. for example this part:
rest.find(({id})=> id === parseInt(currentId)).list
Will look like
rest.find(({id})=> id === parseInt(currentId)) || {list:[]}).list
Which basically means if its undefined return an object that has an empty list so then it will concatenate an empty list which results in being the same list. (like multiplying by 1 in a multiplication)
Hope it helps.
EDIT after your edit.
If your array is in different order you need to find the dictonary and then the logic is the same
const [newHead] = otherArray.filter(({list}) => list.every(elem=>!isNaN(elem)));
const result2 = newHead.list.reduce(
(acc,currentId) =>acc.concat(otherArray.find(({id})=> id === parseInt(currentId)).list),[]);
if you are testing for the flag then your head filter would look like. the blocks are the same the only thing that changes is the condition.
const [newHead] = otherArray.filter(({flag}) => flag));
(note* that instead of using the rest i used the complete array(otherArray). since im targeting equality.
Im using filter and extracting the first element of the result. because im accounting for the possibility that in the future you may have more than one "dictionary element". if thats the case in the future then you just have to concat the lists from the filter result
const array = [
{
id: 10001,
flag: true,
list: ["10002", "10003"]
},
{
flag: false,
id: 10002,
list: ["aaa", "bbb"]
},
{
flag: false,
id: 10003,
list: ["ccc", "ddd"]
}
];
const isHead = item => item.flag && item.id === 10001;
const head = array.find(isHead);
const rest = array.filter(item => !isHead(item));
const result = rest
.flatMap(item =>
head.list.includes(item.id.toString()) && item.list
);
console.log(result);
You can map over the list of the first item and concat all the lists from those ids.
const mapItems = (input) => {
const source = input[0].list;
source.reduce((results, id) => {
return results.concat(input.find(item => item.id === id).list);
}, []);
};
mapItems([
{
"id": 10001,
"list": [
"10002",
"10003"
]
},
{
"id": 10002,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10003,
"list": [
"ccc",
"ddd"
]
}
]);
You can fetch the values of the list of first object in the array as arr[0]['list']
Once you have these values (10002,10003) then you can fetch the list values of remaining objects in the array whose id key matches one of the above values.
if(arr[i]['id'] == 10002 || arr[i]['id'] == 10003){
//fetch the list values
}
I have a data set that I'm pulling in from a database. It's one dimensional and I basically need to make it more structured. I refer to it as "flat".
I need to display a heading, and items under that heading that are related to the heading.
The data comes in as having and section_name (the heading) and item_name (items) and other data unique to each item like download URLs etc.
item_name(item)_______section_name(header)
first_________________Funds
second________________Funds
third_________________Funds
fourth________________Literature
fifth_________________Literature
sixth_________________Literature
seventh_______________Literature
eighth________________DueDilligence
I don't know what any of the names will be for the items or sections, or how many items, sections, or items per section. As I said, it's very flat. This needs to be fully dynamic which is why this is complicating things for me.
Here is what I've done.
API call to retrieve data. Store data in a state as an array (it comes in as an array of objects).
I create an empty array to store my newly structured data.
I loop through the data with a foreach.
I create a new object for my new data to add to the new array so I can loop over it later.
I first check to make sure the data exists.
To create the headers I check to see if my new empty array is actually empty OR my section_name is not the same as the last one.(in the original data array I got from the API call)
I store the section_names as an object in the new array (newArray.push(newObject)
I've gotten this far. Now I need to take the item_names that correlates to the section_names and store them in the object under each header name, or at least in the same index.
_generateInfo() {
let dataArray = this.state.stepTwoData
let newArray =[]
dataArray.forEach(function(item, index) {
let newObject = {}
if (index > 0) {
if (newArray.length === 0 || item.investor_portal_section_name !== dataArray[index -1].investor_portal_section_name) {
newObject["name"] = item.investor_portal_section_name
newObject["items"] = []
newArray.push(newObject)
}
})
console.log(newArray)
}
I tried pushing the items to the "number" array on my new object and that doesn't seem to work properly. Sometimes it will duplicate my newObject.name
Checking if the newObject.name === the section_names in the array and push it to the "number" array in my new object just creates new key-value pairs so it's still not correlating.
I tried looping through again in the if statement and if section_name === newObject.name then create a newObject and push it, but it would only push one of the items repeatedly instead of going through all of them.
I need to loop through and create a header (one header per different section_name). Then add each item that corresponds to the section_name to it. like this
[
{section_name(header): "Funds",
items: [
{
name: item_name,
sku: item_sku,
url: item_url
},
{
name: item_name,
sku: item_sku,
url: item_url
}]
},
{section_name(header):"Literature",
items: [
{name: item_name,
sku: item_sku,
url: item_url
},
{
name: item_name,
sku: item_sku,
url: item_url
}]}
]
Using associative array (dictionary) to segregate you data itmes by categories will do the job.
I've drafted some POC code that illustrates the idea. The key element there is buildAssociativeArray function
const raw_data = [
{item_name: "first", section_name: "Funds"},
{item_name: "second", section_name: "Funds"},
{item_name: "third", section_name: "Funds"},
{item_name: "fourth", section_name: "Literature"},
{item_name: "fifth", section_name: "Literature"},
{item_name: "sixth", section_name: "Literature"},
{item_name: "seventh", section_name: "Literature"},
{item_name: "eighth", section_name: "DueDilligence"},
]
function buildAssociativeArray(data) {
const dictionary = {};
for (var i = 0; i < data.length; i++) {
const item = data[i];
const section = item.section_name;
var dictEntry = dictionary[section];
if (!dictEntry) {
dictEntry = [];
dictionary[section] = dictEntry;
}
dictEntry.push({
name: item.item_name,
// other fields like sku: item_sku or url: item_url may follow here
});
}
return dictionary;
}
const dictionary = buildAssociativeArray(raw_data);
console.log(dictionary);
/*
At this point
dictionary == {
"Funds": [
{
"name": "first"
},
{
"name": "second"
},
{
"name": "third"
}
],
"Literature": [
{
"name": "fourth"
},
{
"name": "fifth"
},
{
"name": "sixth"
},
{
"name": "seventh"
}
],
"DueDilligence": [
{
"name": "eighth"
}
]
}
*/
// Associcative array dictionary itself allows to further solve you task using for (var key in dictionary) {...} operator
// If however you need to obtain the data structure looking exactly like the one in your question you may go further with following function
function transformAssociativeArray(dictionary) {
const array = [];
for (var key in dictionary) {
const items = dictionary[key];
const newEntry = {
section_name: key,
items: items,
}
array.push(newEntry);
}
return array;
}
const array = transformAssociativeArray(dictionary);
console.log(array);
/*
At this point
array == [
{
"section_name": "Funds",
"items": [
{
"name": "first"
},
{
"name": "second"
},
{
"name": "third"
}
]
},
{
"section_name": "Literature",
"items": [
{
"name": "fourth"
},
{
"name": "fifth"
},
{
"name": "sixth"
},
{
"name": "seventh"
}
]
},
{
"section_name": "DueDilligence",
"items": [
{
"name": "eighth"
}
]
}
]
*/
When I make an API request, the API server returns me a JSON object. How do I parse the JSON object to their designated types in Javascript?
This is what is being returned to me:
{
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
So would like to parse the array, classes, the object, food, and the string student_name, and console log them.
You need to use JSON.parse() to do it:
var myData = {
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
var myObject = JSON.parse(myData);
console.log(myObject.student_name); //Output: Joshua
console.dir(myObject) //to see your object in console.
display a single element:
console.log(myData.classes[0]);
display all elements of an array:
var arr = myData.classes;
for(var i in arr)
{
console.log(arr[i]);
}
For more information:
About JSON.parse()
JSON.Parse() Examples
JSON is the JavaScript Object Notation, which means JSON snippets already represent JavaScript objects. You just have to parse them using:
var myObject = JSON.parse(json);
And then you can access:
var myArray = myObject.classes; //should give you an array
console.log(myArray[0]); //should print "A1"
var myFood = myObject.food //should give you a food object with size and type properties
console.log(myFood.size); //should print "slice"
I have an array of objects. if i do a console.log, i can see these array of objects.
[Object, Object, Object, Object,Object]
[0-4]
0:Object
Name: Nikhil
User_ID:123
admin:true
read:false
write:false
1:Object
Name:andy
User_ID:124
admin:false
read:true
write:false
2:Object
Name:Nik
User_ID:125
admin:false
read:false
write:true
3:Object
Name:ranea
User_ID:126
admin:false
read:false
write:true
4:Object
Name:isha
User_ID:127
admin:false
read:true
write:false
Now, if i do JSON.stringify, i get this output.
[{"Name":"Nikhil","User_ID":"123","admin":true,"read":false,"write":false},
{"Name":"andy","User_ID":"124","admin":false,"read":true,"write":false},
{"Name":"Nik","User_ID":"125","admin":false,"read":false,"write":true},
{"Name":"ranea","User_ID":"126","admin":false,"read":false,"write":true},
{"Name":"isha","User_ID":"127","admin":false,"read":true,"write":false}]
Instead of doing stringify to all the parameters, I want to only do it to few. For e.g. I don't want to pass Name. I only want to pass User_ID since it is unique, and admin,read,write properties.
How can i create a new array of objects using loadash and then stringify the result. My final output after JSON.stringify should be like this
[{"User_ID":"123","admin":true,"read":false,"write":false},
{"User_ID":"124","admin":false,"read":true,"write":false},
{"User_ID":"125","admin":false,"read":false,"write":true},
{"User_ID":"126","admin":false,"read":false,"write":true},
{"User_ID":"127","admin":false,"read":true,"write":false}]
Using _.pick it should be:
var newArr = _.map(oldArray,
function(item) {
return _.pick(item, ['User_ID', 'admin', 'read', 'write']);
});
You could make use of the Array.map() function.
var obj = [ { "Name": "Christophe", "Age": 42, "foo": "bar" }, { "Name": "Blah", "Age": 42, "foo": "foo2" }]
var filtered = obj.map(function (element) {
return {
"Name": element.Name
}
});
After that, filtered contains your objects with only the keys you want to keep, and you can JSON.stringify it.
console.log(JSON.stringify(filtered));
// [ {"Name": "Christophe"}, {"Name": "Blah"} ]
You can use this little function to return
the new Array.
var arr = [{
Name: "Nikhil",
User_ID: "123",
admin: "true",
read: "false",
write: "false"
}, {
Name: "andy",
User_ID: "124",
admin: "false",
read: "true",
write: "false"
}];
function returnArr(array) {
var arrNew = arr;
for (let in arrNew) {
delete arrNew[let].Name;
}
return JSON.stringify(arrNew);
}
document.write(returnArr(arr)); // or console.log(returnArr(arr))