angularjs combine 2 objects by property value - javascript

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

Related

Change Object Value using forEach

I am trying to change the value of object from the array but, it's not work as expected. I tried following.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
arrObj.forEach(obj => {
obj = {...obj, ...obj.field}
delete obj.field
})
console.log("after:", arrObj);
Also I found some solution that to use index but, it add index before the object.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "abcd",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
}
]
arrObj.forEach((obj, index) => {
obj[index] = {...obj, ...obj.field}
delete obj.field
})
console.log("after:", arrObj);
How can I do with forEach?
Edit:
I want to remove the field object and assign/overwrite all the property outside.
Using map and assigning the result is probably a better way of doing this, but if you want to use forEach, you need to assign to the original array inside the loop:
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
arrObj.forEach(({ field, ...rest}, idx, orig) => {
orig[idx] = { ...rest, ...field }
})
console.log(arrObj);
I would use map to change an array, but you may have a reason that you wish to modify the original. You could just reassign arrObj to the output of the map.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
const newArr = arrObj.map(( obj ) => {
const {field, ...rest} = obj
return {...field, ...rest}
})
console.log("after:", newArr);

How to Update value nested array in array jquery

Please help
I tried to edit the second myArray, and in myArray there is myArray[data] which is also an array, how do I update it??
var myArray= [
{
"id": 0,
"item": "DONOMULYO",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
"id": 1,
"item": "PAGAK",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
**"id": 2,**
"item": "BANTUR",
"data": [
{
"id": 0,
"field": "satu",
**"record": "11"**
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
},
{
"id": 3,
"item": "SUMBERMANJING WETAN",
"data": [
{
"id": 0,
"field": "satu",
"record": "11"
},
{
"id": 1,
"field": "dua",
"record": ""
}
]
}
]
how to change myArray second data record?
this is my code for change update, but there all data is updated, how to change only myArray third data inside myArray[data] ??
//this is my code for update
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var arr_data_edit = myArray[update_array].data;
if(arr_data_edit[update_inside_array].id == update_inside_array){
arr_data_edit[idfiledx].record = valnya;
}
console.log(myArray);
I've tried various ways, this is the last one I ran out of ideas, please help to solve this
Thank you for the help
Your current code should work if you simply change idfiledx to update_inside_array:
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var arr_data_edit = myArray[update_array].data;
if(arr_data_edit[update_inside_array].id == update_inside_array){
arr_data_edit[update_inside_array].record = valnya;
}
console.log(myArray);
In general, I think it would probably be better to find the item to be updated (the one that has `id: 2`) regardless of its position in the array.
Here's a way to doing that using the .find method of arrays:
const
myArray = [
{ "id": 0, "item": "DONOMULYO", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 1, "item": "PAGAK", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 2, "item": "BANTUR", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]},
{ "id": 3, "item": "SUMBERMANJING WETAN", "data": [
{ "id": 0, "field": "satu", "record": "11" },
{ "id": 1, "field": "dua", "record": "" }
]}
],
outerId = 2,
innerId = 0,
newVal = '12',
outerObj = myArray.find(obj => obj.id == outerId),
innerObj = outerObj.data.find(obj => obj.id == innerId);
innerObj.record = newVal;
console.log(myArray);
.as-console-wrapper{min-height: 100%!important; top: 0}
(Btw, it doesn't look like you use or need any jQuery for this.)
You don't need jQuery, you can use either find or filter, here is an example using filter:
var update_array = 2;
var update_inside_array = 0;
var valnya = '12';
var item = myArray[update_array].data.filter(x => x.id == update_inside_array)[0];
if (typeof item !== 'undefined') item.record = valnya;
console.log(myArray);

Javascript to manipulate array of objects and create two set of arrays for data and link [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an object array like the following.
[
{
"name": "car",
"value": "",
"children": [
{
"name": "v8_engine",
"value": "",
"children": [
{
"name": "cylinder-arrangement",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": []
},
{
"name": "max-elements",
"value": "8",
"children": []
}
]
}
]
},
{
"name": "other-parts",
"value": "",
"children": [
{
"name": "per-cylinder-parts",
"value": "",
"children": [
{
"name": "piston-diameter",
"value": "",
"children": [
{
"name": "type",
"value": "uint32",
"children": []
},
{
"name": "range",
"value": "2000... 9000",
"children": []
}
]
},
{
"name": "valves",
"value": "",
"children": [
{
"name": "number",
"value": "",
"children": []
},
{
"name": "position",
"value": "",
"children": []
}
]
}
]
}
]
}
]
}
]
I want to parse through each elements and their respective childrens and manipulate it to create two set of arrays
Node data array that contains:key which is index of that element and values as shown
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name}) or nodeDataArray.push({ key:i,Data: a.name + " " + a.value})
Link Data array that contains the link (parent child relation ship)
linkDataArray.push({ from: i, to: j });
where i is the index of parent and j is index of child
I have the following function that parses through the elements and pushes them fine in to node data array with index.
vm.tree.forEach(loop);// here vm.tree is the json data, passed dynamically
var i=0;
function loop(a) {
if(a.yang_type!='' && a.name!=''){
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name, group: -1 });
//console.log("Data:",a.yang_type);
linkDataArray.push({ from: i, to: i+1 });
}
if(a.name!='' && a.value!=''){
nodeDataArray.push({ key:i,Data: a.name + " " + a.value, group: -1 });
linkDataArray.push({ from: 0, to: i+1 });
}
i=i+1;
// process you data
//if(Array.isArray(a.children)){j++;}
if(Array.isArray(a.children)){
//var g=0;
a.children.forEach(loop);
}
}
Below wordings is based on the sample JSON to make it more clear on what is my expected output should be
parse through the JSON and list out all the elements in the JSON object as shown below
car
v8_engine
cylinder-arrangement
type string
max-elements 8
other_parts
per-cylinder-parts
piston-diameter
type UINT32
range 2000...3000
valves
number
position
Then list of relationship based on parent and child index. Where car is the 0th element,v8_engine is the 2nd and so on … until the last one which is position being 12th
So we have total of 13 elements from the above example. Now I need to list their relation ship too. Like
0th element is parent of 1 and 5.
1st element is parent of 2
2nd element is parent of 3 and 4
and so on
To generate the parent list, you could use a closure with a from variable, which holds the node number from where it has been called.
BTW, your list above is not correct for 5th element is parent of 6 and 10.
function loop(from) {
return function (a) {
var f = i;
if (from !== undefined) {
linkDataArray.push({ from: from, to: i });
}
i++;
if (Array.isArray(a.children)) {
a.children.forEach(loop(f));
}
};
}
var data = [{ "name": "car", "value": "", "children": [{ "name": "v8_engine", "value": "", "children": [{ "name": "cylinder-arrangement", "value": "", "children": [{ "name": "type", "value": "string", "children": [] }, { "name": "max-elements", "value": "8", "children": [] }] }] }, { "name": "other-parts", "value": "", "children": [{ "name": "per-cylinder-parts", "value": "", "children": [{ "name": "piston-diameter", "value": "", "children": [{ "name": "type", "value": "uint32", "children": [] }, { "name": "range", "value": "2000... 9000", "children": [] }] }, { "name": "valves", "value": "", "children": [{ "name": "number", "value": "", "children": [] }, { "name": "position", "value": "", "children": [] }] }] }] }] }],
i = 0,
linkDataArray = [];
data.forEach(loop());
console.log(linkDataArray);
var i=0;
var nodeDataArray = [];
var linkDataArray = [];
function loop(from) {
return function (a) {
var f = i;
if(a.yang_type!='' && a.name!=''){
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name, group: -1 });
//c=c+a.name;
//console.log("c:",c);
//console.log("Data:",a.yang_type);
//linkDataArray.push({ from: i, to: i+1 });
}
if(a.name!='' && a.value!=''){
nodeDataArray.push({ key:i,Data: a.name + " " + a.value, group: -1 });
//c=c+a.name+a.value;
console.log("c:",c);
//linkDataArray.push({ from: 0, to: i+1 });
}
if (from !== undefined) {
linkDataArray.push({ from: from, to: i });
}
i++;
if (Array.isArray(a.children)) {
a.children.forEach(loop(f));
}
//console.log("c:",c);
};
}
var data = [{ "name": "car", "value": "", "children": [{ "name": "v8_engine", "value": "", "children": [{ "name": "cylinder-arrangement", "value": "", "children": [{ "name": "type", "value": "string", "children": [] }, { "name": "max-elements", "value": "8", "children": [] }] }] }, { "name": "other-parts", "value": "", "children": [{ "name": "per-cylinder-parts", "value": "", "children": [{ "name": "piston-diameter", "value": "", "children": [{ "name": "type", "value": "uint32", "children": [] }, { "name": "range", "value": "2000... 9000", "children": [] }] }, { "name": "valves", "value": "", "children": [{ "name": "number", "value": "", "children": [] }, { "name": "position", "value": "", "children": [] }] }] }] }] }]
data.forEach(loop());

Filter an array of objects / convert array into another

could you please help me to convert data in format like :
"tanks": [
{
"id": "1",
"name": {
"id": 1,
"tor": "000"
},
"type": {
"id": 1,
"system": "CV-001"
}
}
]
into
"tanks":[
{
"type": 1,
"name": 1
}
]
As you can see, type.id in the first array is the same as just type in the second. It is like I have to iterate through the array(as I have not only one Object in it) and left only needed fields in Objects, but I am stuck.
Hope it is a little informative for you.
You can do this with a simple Array.map()
var obj = {
tanks : [
{
"id": "1",
"name": {
"id": 1,
"tor": "000"
},
"type": {
"id": 1,
"system": "CV-001"
}
},
{
"id": "2",
"name": {
"id": 2,
"tor": "200"
},
"type": {
"id": 2,
"system": "CV-002"
}
}
]
};
obj.tanks = obj.tanks.map(function(item) {
return {
name : item.name.id,
type : item.type.id
};
});
console.log(obj);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Add new property to objects in an array based of a seperate array

I have 2 arrays with objects in them. I am trying to make a new array based on the information provided in the original 2 arrays. I have jQuery and Underscore available.
The 2 arrays look like the following:
var orgArray = [
{
"name": "phone",
"value": "123-456-7890"
},
{
"name": "color",
"value": "blue"
},
{
"name": "city",
"value": "San Diego"
},
{
"name": "zip",
"value": "54321"
},
{
"name": "email",
"value": "something#somewhere.com"
},
{
"name": "state",
"value": "CA"
},
{
"name": "Sale",
"value": "On Sale"
}
];
var configArray = [
{
"columns": ["phone", "city", "zip"],
"target": "phone"
},
{
"columns": ["email", "state"],
"target": "email"
}
];
If configArray[i].columns contains a string that is in orgArray[i].name then add the target property to the orgArray's object. Here is the new Array that I am trying to create:
var newArray = [
{
"name": "phone",
"value": "123-456-7890",
"target": "phone"
},
{
"name": "color",
"value": "blue"
},
{
"name": "city",
"value": "San Diego",
"target": "phone"
},
{
"name": "zip",
"value": "54321",
"target": "phone"
},
{
"name": "email",
"value": "something#somewhere.com",
"target": "email"
},
{
"name": "state",
"value": "CA",
"target": "email"
},
{
"name": "Sale",
"value": "On Sale"
}
];
Here is my current JS and a fiddle:
jsFiddle: http://jsfiddle.net/9Dv2f/
var newArray = [];
_.each(orgArray, function(element, index, list) {
_.each(configArray, function(elem, i) {
_.each(elem.columns, function (el, x) {
if (element.name === el.name) {
console.log(element.name);
newArray.push({
name: element.name,
value: element.value,
target: elem.target
});
}
});
});
});
console.log(newArray);
Using $.each() you can do:
$.each(orgArray, function(i, org){
$.each(configArray, function(j, config){
if(config.columns.indexOf(org.name) > -1){
orgArray[i].target = config.target;
}
});
});
DOCUMENTATION
You should test if the name exists in elem.column, you can do this by using the .indexOf function. The .indexOf function returns the index of the found object (starting from 0), if it isn't found it will return -1.
if(elem.columns.indexOf(element.name) > -1)
FIDDLE
Something underscore way, not sure(didn't confirmed), should work.
Copy the array and map it to updated based on your condition.
var newArray = orgArray;
_.map(newArray, function(elem){
_.each(configArray, function(elem_config, i) {
if(_.contains(elem_config, newArray.name)){
return newArray['target'] = elemconfig.target
}
}
}

Categories

Resources