Want to add an array of objects inside a nested object: Javascript - javascript

I need to add an array of objects to an another object whose structure has been shown below.
Here arr is the array of objects that needs to be added to "dest" object.
Help would be appreciated
structure:
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
This array of objects needs to added to an object of following structure:
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
I would want add the fields of "arr" inside "sequence" so that result would something like this:
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
},
{
"field": "state",
"value": "value2",
},
{
"field": "city",
"value": "value3",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}

Using forEach() you can do it.
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
arr.forEach(function (item) {
dest.filter.sequence.push(item)
});
console.log(dest)
Also ES6 spread operator can be used to merge
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
dest.filter.sequence.push(...arr)
console.log(dest)

You just need to use below code to insert array into object.
arr.forEach( function(value, index, array) {
dest.filter.sequence.push(value);
});

Related

Filter and get data from JSON

How to get the data value from the list, the size of the array, the main thing is not through the index, because the order of the arrays can change and I can get specific data from the code === "size". Unfortunately, the structure cannot be changed. It came to mind only through the filter, by index, but it is impossible
The result should be 100 150
https://jsoneditoronline.org/#left=cloud.b10638604c214b189f87747414e06035
[
[
"color",
{
"name": "Цвет",
"code": "color",
"list": [
{
"value": "Зеленый"
},
{
"value": "Красный"
}
]
}
],
[
"size",
{
"name": "Размер",
"code": "size",
"list": [
{
"value": "100"
},
{
"value": "150"
}
]
}
]
]
This data structure is terrible, but a quick fix could be something like this
const data = [
[
"color",
{
"name": "Цвет",
"code": "color",
"list": [
{
"value": "Зеленый"
},
{
"value": "Красный"
}
]
}
],
[
"size",
{
"name": "Размер",
"code": "size",
"list": [
{
"value": "100"
},
{
"value": "150"
}
]
}
]
]
const size = data.filter(element => element[1].code === 'size')[0][1].list.map(element => element.value)
console.log(size)

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

Load nested object on an array dynamically with javascript

I have a json data in this format and I would like to load data in an array which is an object, without hard coding the object keys. I would like to get items and labels in each category and each category has it name for object key. At the moment I get the data by
...myData.labels.name; or ...items.name; which is not effective because
the name changes depending on the category.
[
[
{
"key": "mykey",
"category": "myCategoryKey",
"category_label": "myCategoryLabel",
"field": "filter",
"items": {
"name": [
"item1",
"item2"
]
},
"labels": {
"name": [
"Item1",
"Item2"
]
}
},
{
"key": "mykey2",
"category": "myCategoryKey2",
"category_label": "myCategoryLabel2",
"field": "filter",
"items": {
"name2": [
"item1",
"item2"
]
},
"labels": {
"name3": [
"Item1",
"Item2"
]
}
}
]
]
Use Object.keys() to get Keys for items present if values change dynamically.
And then use the keys to get corresponding values.
var data = {
"key": "mykey2",
"category": "myCategoryKey2",
"category_label": "myCategoryLabel2",
"field": "filter",
"items": {
"name2": [
"item1",
"item2"
]
},
"labels": {
"name3": [
"Item1",
"Item2"
]
} }
var labelsPresent = Object.keys(data.labels);
console.log(labelsPresent);
var labelValues= labelsPresent[0];
console.log(data.labels[labelValues]);

How to convert array of objects to object with index?

I have a array like this->
var jsonResponse = [
{
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
{
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
And I want to convert it to ->
{
"abc" : {
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
"ccc": {
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?
let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)
console.log(JSON.stringify(indexedResult));

angularjs combine 2 objects by property value

I have 2 different object arrays which i would like to merge according to the "id" value.
So if my first array looks like this:
[
{
"id": "75318408571184",
"component": "textInput",
"index": 0,
"label": "Text",
"description": "description",
"placeholder": "placeholder",
},
{
"id": "9463537670672",
"component": "textArea",
"index": 1,
"label": "Paragraph",
"description": "description",
"placeholder": "placeholder"
}
]
and my second one looks something like this:
[
{
"id": "75318408571184",
"value": "value1"
},
{
"id": "9463537670672",
"value": "value2"
}
]
i would like to get this array of objects:
[
{
"id": "75318408571184",
"component": "textInput",
"index": 0,
"label": "Text",
"description": "description",
"placeholder": "placeholder",
"value": "value1"
},
{
"id": "9463537670672",
"component": "textArea",
"index": 1,
"label": "Paragraph",
"description": "description",
"placeholder": "placeholder",
"value": "value2"
}
]
is there a neat way to do this in angular or javascript without looping through the array?
try this:
var result = firstArray.map(function(item) {
var second = secondArray.find(function(i) {
return item.id === i.id;
});
return second ? Object.assign(item, second) : item;
});
console.log(result);
Array.prototype.map() applies function in argument on each item of firstArray and returns new array with modified values.
Object.assign() is function which copies properties of second object to the item object in the code above.
The above answers are already good. But if you want to look at some other libraries you can have a look at this .
loadash merge
var object = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var other = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(object, other, function(a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
In plain Javascript, you can use Array.prototype.forEach() and Array.prototype.some()
var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }];
obj2.forEach(function (a) {
obj1.some(function (b) {
if (a.id === b.id) {
b.value = a.value;
return true;
}
});
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');
Another possibility is to build a hash table temp first and then manipulate the item directly.
var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }],
temp = {};
obj1.forEach(function (a, i) {
temp[a.id] = i;
});
obj2.forEach(function (a) {
obj1[temp[a.id]].value = a.value;
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');

Categories

Resources