Javascript: Make new array out of nested json object - javascript

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);
});

Related

Compare array of objects with array

I have an array of objects:
arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
and a simple array:
arr2 = [ 2, 5 ]
I want to write a method that returns true if one of the object ids from arr1 can be found in arr2. So I could use it with
v-if
later.
What's your suggestion?
let arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
let arr2 = [ 2, 5 ]
let arr1_id = arr1.map(function (obj) {
return obj.id;
});
function check(array1, array2) {
let intersection = array1.filter(element => array2.includes(element));
if (intersection.length > 0) {
return true
}
else {return false}
}
bool = check(arr1_id,arr2)
console.log(bool)

copying data from one array to another array

Array One:
array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}]
Array Two:
array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
Resulting Array:
resultingArray = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}],
"a_id" : {"id": 5, "name": "bcd"}
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}],
"a_id" : {"id": 4, "name": "bef"}
}]
I am looking to add the array2 objects into array1 based on id's of array2. I have tried using map function on both the arrays to compare and add the object but I didn't succeed. Can you please suggest me how to do it?
Thank you
Add the array2 objects into array1 based on ids of array2.
let array1 =
[
{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}
];
let array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}
];
let resultingArray=[];
array1.forEach(function(element) {
element['a_id'] = [];
element['attr'].forEach(function(attr) {
element['a_id'].push(array2.find(function(item) {
return item.id == attr.value;
}));
});
resultingArray.push(element)
});
console.log(resultingArray);
I presume you intend to extract the object whose ID is equal to the value field the in the each object in array1.
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var resultingArray = [];
for(var i = 0; i < array1.length; i++) {
resultingArray[i] = array1[i];
for(var j = 0; j < array2.length; j++) {
if(resultingArray[i].attr[0].attr_code.value === array2[j].id) {
resultingArray[i].push("a_id": array2[j]);
}
}
}
You just need to lop through array1, and for each object in array1, you need to find corresponding objects in array2 which match the criterion.
You can use array map and array index to do:
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var result = array1.map(current=>{
//find index of attr in array2
let index = array2.findIndex(c=>{
if (c['id']===(Number(current['attr'][0]['value'])))
return c;
});
current["a_id"] = array2[index];
return current;
});
console.log(result);
Please check if the following code suites your requirement. You may need to make some changes.
function mergeArrays3 (arr1, arr2) {
return arr1.map((value, index) => {
let object = null;
let result = {...value};
for (let element of arr2) {
if (element.id == parseInt(value.attr[0].value)) {
object = element;
break;
}
}
if (object != null) {
let attr = value.attr[0];
if (attr.hasOwnProperty("attr")) {
result[value.attr[0].attr] = object;
} else if (attr.hasOwnProperty("attr_code")) {
result[value.attr[0].attr_code] = object;
}
}
return result;
});
}
I loop over first array and find an element in second array matching id of value.attr[0].value. If found then i added this object in the first array at key of value.attr[0].attr or value.attr[0].attr_code.
I have tried using map function on both the arrays to compare and add
the object but I didn't succeed
Below is the functional programming approach using map():
/* GIVEN */
const array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{
"attr_code": "a_id",
"value": "5"
}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{
"attr": "a_id",
"value": "4"
}]
}
]
const array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
/* From array2, make an object keyed by the 'id' field. We'll use this as a key-value lookup table */
const lookupTable = array2.reduce((accum, item) => {
accum[item.id.toString()] = item
return accum
}, {})
console.log('***LOOKUP TABLE***\n', lookupTable) // result is an object we use to lookup
/* From array1, we append data from the lookup table */
const final = array1.map(item => {
item.a_id = lookupTable[item.attr[0].value]
return item
})
console.log("***RESULT***\n", final)
Hope this helps.
Cheers,

Finding object through list of objects by finding a specific value

I have list of dynamic objects. Dynamic because the numeric identity of the objects under data are always changing/increasing. I already have a variable that is defined as the amount of objects under data. The variable is as follows
var numOfFruits = Object.keys(Fruits.data).length
Then to go through each object under data I run this loop
for(numOfFruits in Fruits.data) {
var objectsUnderData = Fruits.data[numOfFruits];
}
I am wanting to be able to request the numeric identity of an object containing a certain value such as "Banana", "Apple", or "Grape". So I want to be able to use a pre-defined variable like var name = "Apple" and get the identity of the object it's in.
{
"type": "fruits",
"data": {
"1": {
"id": 1,
"key": "Banana",
"name": "Banana",
},
"2": {
"id": 2,
"key": "Orange",
"name": "Orange",
},
"3": {
"id": 3,
"key": "Grape",
"name": "Grape",
},
"4": {
"id": 4,
"key": "Apple",
"name": "Apple",
}
}
}
My Question: How do I use a specific value (name: "Apple", name: "Banana", etc...) to find the identity of the object it is under.
See function fruitFinder below:
function fruitFinder (Fruits, name) {
for (fruit in Fruits.data) {
if (Fruits.data[fruit].name == name) {
return Fruits.data[fruit].id;
}
}
}
var Fruits = {
"type": "fruits",
"data": {
"1": {
"id": 1,
"key": "Banana",
"name": "Banana",
},
"2": {
"id": 2,
"key": "Orange",
"name": "Orange",
},
"3": {
"id": 3,
"key": "Grape",
"name": "Grape",
},
"4": {
"id": 4,
"key": "Apple",
"name": "Apple",
}
}
};
var name = "Apple";
console.log(fruitFinder(Fruits, name));

Need to merge objects with the same keys but different values

I want to find the shortest and most beautiful way to convert an array of objects with the same values of the category key:
[{
"label": "Apple",
"category": "Fruits"
}, {
"label": "Orange",
"category": "Fruits"
}, {
"label": "Potato",
"category": "Vegetables"
}, {
"label": "Tomato",
"category": "Vegetables"
}, {
"label": "Cherry",
"category": "Berries"
}]
to the one with grouped labels from the same category:
[{
"label": ["Apple", "Orange"],
"category": "Fruits"
}, {
"label": ["Potato", "Tomato"],
"category": "Vegetables"
}, {
"label": ["Cherry"],
"category": "Berries"
}]
You could use an object as hash table and group the categories.
var data = [{ "label": "Apple", "category": "Fruits" }, { "label": "Orange", "category": "Fruits" }, { "label": "Potato", "category": "Vegetables" }, { "label": "Tomato", "category": "Vegetables" }, { "label": "Cherry", "category": "Berries" }],
grouped = [];
data.forEach(function (a) {
if (!this[a.category]) {
this[a.category] = { label: [], category: a.category };
grouped.push(this[a.category]);
}
this[a.category].label.push(a.label);
}, Object.create(null));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's how I would do this using lodash:
_(coll)
.groupBy('category')
.map((v, k) => ({
category: k,
label: _.map(v, 'label')
}))
.value()
Basically, groupBy() creates an object with unique categories as keys. Then, map() turns this object back into an array, where each item has the structure you need.
Here is my attempt to solve your problem
var result = [];
var input = [{
"label": "Apple",
"category": "Fruits"
}, {
"label": "Orange",
"category": "Fruits"
}, {
"label": "Potato",
"category": "Vegetables"
}, {
"label": "Tomato",
"category": "Vegetables"
}, {
"label": "Cherry",
"category": "Berries"
}];
var cat = [];
for(i = 0; i < input.length; i++) {
if(!cat[input[i].category]) {
cat[input[i].category] = {category: input[i].category, label:[input[i].label]};
result.push(cat[input[i].category]);
} else {
cat[input[i].category].label.push(input[i].label);
}
}
console.log(result);

parsing javascript array object to create new javascript array

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.

Categories

Resources