parsing javascript array object to create new javascript array - javascript

My sample javascript array format which I get from server:
var json =[
{
"id": "1",
"tagName": [
{
"fruit": "apple"
},
{
"fruit": "watermelon"
}
]
},
{
"id": "2",
"tagName": [
{
"fruit": "orange"
},
{
"fruit": "pineapple"
}
]
},
{
"id": "3",
"tagName": [
{
"fruit": "banana"
},
{
"fruit": "guava"
}
]
}
];
I need to create a javascript function which will generate an array from the above array which will be like this
var json1 = ["1", "2", "3"]
AND
var json1a = [{ "id": "1" }, { "id": "2" }, { "id":"3" }]
All help is sincerely appreciated
Thanks

You simply need to iterate through the array:
var json1 = [];
var json1a = [];
for (var i = 0; i < json.length; i++){
json1.push(json[i].id);
json1a.push({id: json[i].id});
}
If I may advise, you IDs should be Numbers, instead of strings. In this case, you would use:
json1.push(json[i].id);
json1a.push({"id", json[i].id});
Here is an updated fiddle.

Related

Returning parent key based on a value in a list of arrays in Javascript

{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
This is list of arrays with keys and values as array, I want to return all the keys based on a particular value;
For Eg:
I want to return the parent keys which are [arr1,arr2], reason being both the arrays contain a value Unique, So I want to return the parent key of both the values, which is arr1 and arr2 respectively.
Note: The list can have n numbers of arrays.
Any help would be appreciated. Thanks in advance.
The simplest way to go about this is:
Loop through the keys in your object
Check if the array contains any objects with the name "Unique"
If so, add the objects key to an array
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
This is a more generic approach:
const getKeysByValue = (data, value) => {
const dataKeys = Object.keys(data);
const valueKey = Object.keys(value);
return dataKeys.filter(currKey => {
for(let element of data[currKey])
if(element[valueKey] === value[valueKey])
return true;
});
}
const data = {
"arr1":[
{
"name":"something1",
"shape": "Trapezium",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"shape": "Octagon",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"shape": "Square",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"shape": "Triangle",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"shape": "Circle",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"shape": "Triangle",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
}
],
"arr3":
[
{
"name":"Not-Unique",
"shape": "Circle",
"id":"8hcf14ee58ea25g343e9a2f208df215c"
}
]
}
console.log(getKeysByValue(data, {"name": "something2"})); // ["arr1"]
console.log(getKeysByValue(data, {"name": "Unique"})); // ["arr1", "arr2"]
console.log(getKeysByValue(data, {"shape": "Circle"})); // ["arr1", "arr3"]
console.log(getKeysByValue(data, {"shape": "Square"})); // ["arr1"]
The function receives two parameters, data and value. value is expected to be in the format of the value you are looking to filter with. In your example you wanted it to be "Unique" and in each object in the array it was presented like "name": "Unique" so we will send it as an object, {"name": "Unique"}.
In this way you can have different value to filter with. In the example above I added a shape key and value to each element, we can filter by this value too as shown in the example above.
you can do like this :
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
arr=[]
//loop over dict with pair keys and value
for (const [key, value] of Object.entries(obj)) {
//get the list of name from dict and check it if it contains Unique string
value.map(e=>e.name).includes("Unique") ? arr.push(key) : false
}
console.log(arr)
You can use array some method
const data = {
"arr1": [{
"name": "something1",
"id": "233111f4-9126-490d-a78b-1724009fa484"
},
{
"name": "something2",
"id": "50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name": "something4",
"id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name": "something5",
"id": "ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2": [{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
}]
}
var obj = [],
keys;
for (keys in data) {
data[keys].some(a => "Unique" === a.name) && obj.push(keys);
}
console.log(obj);
An alternative way that i could think of is using Regexp
var obj = {
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
let str = JSON.stringify(obj);
let match = str.matchAll(/\"([\w\d]+)\":\[(?:{[\s\S]+},)*{\"name\":\"Unique\"/g);
let parent = [];
for(let m of match){
parent.push(m[1]);
}

How to iterate over a http response(json) in angular service method, to generate a customized json?

I am getting http response like this:
[
{"id": "1", "name": "2", "value": "3", "any": "4"}
]
I want to convert it to something like this:
[
{
"heading": "id"
"content": "1"
},
{
"heading": "name"
"content": 2
},
{
"heading": "value"
"content": 3
},
{
"heading": "any"
"content": 4
}
]
I am using angular4.0.0 and I want to perform this in service method.
How to achieve this result?
Here you go :
var arrayData = [
{"id": "1", "name": "2", "value": "3", "any": "4"}
]
let finalArray = arrayData.map(el => {
let returnArray = [];
for(let key in el){
returnArray.push({heading : key , content : el[key]})
}
return returnArray;
})
console.log(finalArray);
var response = [
{"id": "1", "name": "2", "value": "3", "any": "4"}
];
var newJson = [];
response.forEach(function(val,index){
Object.keys(val).forEach(function(data) {
newJson.push({heading: data,content:val[data]})
})
console.log(newJson)
})
var responseData=[
{"id": "1", "name": "2", "value": "3", "any": "4"}
];
var finalResult = [];
responseData.map(function(item){
var test = [];
var allKeys=Object.keys(item);
for(i=0;i<allKeys.length;i++)
{
finalResult.push({'heading':allKeys[i],'content':item[allKeys[i]]});
}
});
console.log(finalResult)

Hierarchical json to flat with parent ID

I have Hierarchical JSON and want to convert to flat JSON without parent child.
vm.str = [
{
"s_gid": 0,
"title": "scholastic Master List 2016",
"nodes": [
{
"Id": "1",
"templateId": "1",
"s_gid": "10",
"m_s_p_id": "1",
"subject_group_name": "xxxxxxx",
"parent_id": "1",
"sname": "",
"nodes": [
{
"Id": "2",
"templateId": "1",
"s_gid": "100",
"m_s_p_id": "0",
"subject_group_name": "abc",
"parent_id": "10",
"sname": "",
"nodes": [
{
"Id": "3",
"templateId": "1",
"s_gid": "1000",
"m_s_p_id": "0",
"subject_group_name": "efg",
"parent_id": "100",
"sname": ""
}
]
}
]
}
]
}
]
what to convert to new vm.str2 = [] as flat, all nodes at same level without nodes ... sub nodes..
You can use recursive function to return one array of objects
var arr =[{"s_gid":0,"title":"scholastic Master List 2016","nodes":[{"Id":"1","templateId":"1","s_gid":"10","m_s_p_id":"1","subject_group_name":"xxxxxxx","parent_id":"1","sname":"","nodes":[{"Id":"2","templateId":"1","s_gid":"100","m_s_p_id":"0","subject_group_name":"abc","parent_id":"10","sname":"","nodes":[{"Id":"3","templateId":"1","s_gid":"1000","m_s_p_id":"0","subject_group_name":"efg","parent_id":"100","sname":""}]}]}]}]
function flatten(data) {
var result = [];
data.forEach(function(o) {
var obj = {}
for(var e in o) {
(Array.isArray(o[e])) ? result.push(...flatten(o[e])) : obj[e] = o[e];
}
result.push(obj)
})
return result;
}
console.log(flatten(arr))
You could use Array.prototype.reduce() plus recursion for this task:
function getNodes(inputArr) {
return inputArr.reduce(function (prev, value) {
return prev.concat(
[ value ],
(value.nodes ? getNodes(value.nodes) : [])
);
}, []);
}
If you still want to remove nodes, you could either use Array.prototype.map or even Array.prototype.each:
output = output.map(function (value) {
value.nodes = undefined;
return value;
});

Return unique array values from an array inside an array of objects

I can't find a similar question and I'm a bit stuck. I have the following JSON array:
[
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
]
I'm trying to create an array of all the unique elements in the "Attributes" property, but I'm having trouble looping through each object, and then looping through the array elements to return the unique values. I'm trying to do it with filter(), or map() preferably.
EDIT: I want an array of unique elements, so: [1,2,3].
You could do it with couple of Array methods. For example:
var result = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
]
// map to [ ["1", "2"], ["1", "3"], [] ]
.map(item => item.Attributes)
// flatten to [ "1", "2", "1", "3" ]
.reduce((prev, curr) => prev.concat(curr), [])
// filter unique [ "1", "2", "3" ]
.filter((item, i, arr) => arr.indexOf(item) === i)
console.log(result)
If lodash is an option, you can easily get what you want:
> _.chain(foo).map('Attributes').flatten().uniq().value()
["1", "2", "3"]
You can use Array#reduce and Array#filter methods
var data = [{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1", "3"]
}, {
"Name": "element3",
"Attributes": []
}
]
console.log(
// iterate over array elements
data.reduce(function(arr, ele) {
// push the unique values to array
[].push.apply(arr,
// filter out unique value
ele.Attributes.filter(function(v) {
// check element present in array
return arr.indexOf(v) == -1;
})
);
// return the unique array
return arr;
// set initial argument as an empty array
}, [])
);
With ES6 arrow function
var data = [{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1", "3"]
}, {
"Name": "element3",
"Attributes": []
}
]
console.log(
data.reduce((arr, ele) => ([].push.apply(arr, ele.Attributes.filter((v) => arr.indexOf(v) == -1)), arr), [])
);
let uniqueSet = new Set()
let a = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
]
for(let i=0; i<a.length; i++){
a[i].Attributes.map((x) => uniqueSet.add(x))
}
console.log([...uniqueSet])
var uniqueArr = [];
var arr = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
];
arr.forEach(function(obj) {
var attr = obj.Attributes;
attr.forEach(function(val){
if (uniqueArray.indexOf(val) < 0) {
uniqueArray.push(val)
}
});
})
You have answers to choose from. Just for fun: this one uses es6
"use strict";
let uniqueAttr = [];
const obj = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
];
obj.forEach( element =>
element.Attributes.forEach(
attr => uniqueAttr.indexOf(attr) < 0 && uniqueAttr.push(attr)
)
);
document.querySelector("#result").textContent = uniqueAttr;
<pre id="result"></pre>
Try This, It'll help to solve this problem.
var data = [{
"Name": "element1",
"Attributes": ["1", "2"]
}, {
"Name": "element2",
"Attributes": ["1", "3"]
}, {
"Name": "element3",
"Attributes": []
}];
var Attributes = [];
$.each(data, function(i, e) {
$.each(e.Attributes, function(i, e) {
Attributes.push(parseInt(e));
});
});
Attributes = $.unique(Attributes);
alert(Attributes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
With ES6/ES2015 you can use Set and the spread operator:
const input = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
];
const output = [...new Set([].concat(...input.map(item => item.Attributes)))];
console.log(output);
Explanation (from the inside out):
input.map(item => item.Attributes) produces an array of the Attributes arrays
[].concat(...) flattens the arrays, i.e. produces an array of all the Attributes values (including duplicates)
new Set() produces a Set from the array, i.e. stores only the unique Attribute values
[...] produces an array from the Set's values, i.e. produces an array of all unique Attribute values
Building on top of #dfsq answer, you could replace the two map and reduce with a single flatMap
var result = [
{
"Name": "element1",
"Attributes": ["1", "2"]
},
{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
]
// map & flatten to [ "1", "2", "1", "3" ]
.flatMap(item => item.Attributes)
// filter unique [ "1", "2", "3" ]
.filter((item, i, arr) => arr.indexOf(item) === i)
console.log(result)

Javascript: Make new array out of nested json object

I am getting data back which includes nested json objects and would like to make a new array containing those json objects. So if I am getting
[
{
"number": 1,
"products": [
{
"fruit": "apple",
"meat": "chicken"
},
{
"fruit": "orange",
"meat": "pork"
}
]
}
]
I would like the new array to be
[
{
"fruit": "apple",
"meat": "chicken"
},
{
"fruit": "orange",
"meat": "pork"
}
]
var A = [ { "number": 1, "products": [ { "fruit": "apple", "meat": "chicken" }, { "fruit": "orange", "meat": "pork" } ] } ];
var B = [];
A.forEach(function(number) {
B = B.concat(number.products);
});
console.log(B);
or test here
Use for loops to iterate over the data and place it in a new array.
var data = [{
"number": 1,
"products": [{
"fruit": "apple",
"meat": "chicken"
}, {
"fruit": "orange",
"meat": "pork"
}]
}],
allProducts = [];
for(var i=0;i< data.length; i++) {
var products = data[0].products;
for(var j=0;j< products.length; j++) {
allProducts.push(products[j]);
}
}
console.log(allProducts);
Fiddle
This is assuming you want to flatten the products into a single array - I'm probably wrong about that... To test it, I moved a product into a separate parent in the data array.
var data = [
{
"number": 1,
"products": [
{
"fruit": "apple",
"meat": "chicken"
}
]
},
{
"number": 2,
"products": [
{
"fruit": "orange",
"meat": "pork"
}
]
}
];
var products = data.reduce(function(x, y) {
return x.products.concat(y.products);
});

Categories

Resources