Convert Json Array to single Object in Node JS [duplicate] - javascript

This question already has answers here:
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I want to convert JSON array to a single object. PFB the details
Array:
[{ "item-A": "value-1" }, { "item-B": "value-2" }]
Expected Result:
{ "item-A": "value-1", "item-B": "value-2" }
I have tried following options but result is not what I was expecting
let json = { ...array };
json = Object.assign({}, array);
json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
Result:
{"0":{"item-A":"value-1"},"1":{"item-B":"value-2"}}

You can use Object.assign and spread the array
const arr=[{ "item-A": "value-1" }, { "item-B": "value-2" }];
console.log(Object.assign({},...arr));

You can use reduce like how you did it with more attention like this:
let array = [{ "item-A": "value-1" }, { "item-B": "value-2" }];
let object = array.reduce((prev, curr) => ({ ...prev, ...curr }), {});
console.log(object);

Related

How can I filter nested objects with unknown keys? [duplicate]

This question already has answers here:
Iterate through object properties
(31 answers)
Best way to find nested property by name in object
(3 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 months ago.
I'd like to create a new array with information filtered from a nested object with unknown keys.
The data comes from CUPS API and the keys are printer names.
I'd like to filter on for example 'printer-state' === 3.
const data = {
'Expedition': {
'printer-is-shared': false,
'printer-state': 4,
'printer-state-message': '',
'printer-state-reasons': ['none'],
},
'Serverroom': {
'printer-is-shared': false,
'printer-state': 3,
'printer-state-message': '',
'printer-state-reasons': ['none'],
}
}
Thanks
I've tried Array.filter() but couldn't get it to work.
const data = {
'Expedition': {
'printer-is-shared': false,
'printer-state': 4,
'printer-state-message': '',
'printer-state-reasons': ['none'],
},
'Serverroom': {
'printer-is-shared': false,
'printer-state': 3,
'printer-state-message': '',
'printer-state-reasons': ['none'],
}
}
const filterObjectByKeyValue = (obj, key, value) => {
return Object.keys(obj)
.filter(k => obj[k][key] === value)
.reduce((res, k) => ((res[k] = obj[k]), res), {});
};
console.log(filterObjectByKeyValue(data,'printer-state',3))

How to find duplicate values in object and push in array to create distinct array of objects in Angular8 [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed last year.
I am getting below response from API, but i want to format it for iteration to reach the correct values.
In below objects, i am getting column makeLineName and based on this column, i want to create one types array and push whole object as it is on types array.
Suppose for ex - In below response, We have 2 objects for "makeLineName":"Red", So i want to create one types array and push all object inside types array whose matching makeLineName = Red. Thats it.
const data = [{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch"
},
{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}
];
Expected Output
const data = [{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch & crunch"
types :[{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch"
}]
},
{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
types :[{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}
}];
I did below code, it was working fine, but it is creating many nested arrays for types and because of this i am facing issue in iterating with loop to get the perfect value of types array.
getMakeLineMasterData() {
const data = {
data1: 'India'
};
this.testfile.getWork(data).pipe(map(data => this.processData(data))).subscribe((resp: any) => {
if (resp) {
console.log(this.dataSource, "resp");
}
});
}
processData(data: any) {
let mappedData = [];
for (const item of data) {
const mitem = mappedData.find(obj => obj.makeLineName == item.makeLineName);
if (mitem) {
mitem['types'].push(item);
} else {
let newItem = item;
newItem['types'] = [item];
mappedData.push(newItem);
}
}
return mappedData;
}
Right now my code is working and returning data but it is creating many nested arrays for types inside and inside likewise..
Can anyone help me to make it proper as per my expected output.
Issue: circular structure
You are pushing the array inside itself.
eg:
let object1 = { property: [] , cat:1 };
object1.property = [object1];
or
let object1 = { property: [object1] };
// here object1 is pointing to to itself, due to pass by reference.
//that is why you are seeing a never ending nesting of itself (circular);
Correction of your code:
let processData = (data: any) => {
let mappedData = [];
for (const item of data) {
const mitem = mappedData.find(obj => obj.makeLineName === item.makeLineName);
if (mitem) {
mitem['types'].push(item);
} else {
let newItem = { ... item }; //** creating a new object with copied properties
newItem['types'] = [item];
mappedData.push(newItem);
}
}
return mappedData;
}

how to get an object inside an array with a value [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 1 year ago.
Array looks list :
[
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
]
I have a value i.e Uid 673bjhbjhdcsy, how do I check if that Uid exists in the array and get the whole object associated with the Uid.
You can use find like:
const data = [
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
];
console.log(data.find(x => x.Uid === '673bjhbjhdcsy'));
Reference:
Array.prototype.find()
result = [
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
].find(item => item.Uid === '673bjhbjhdcsy')

Get value from object in array: js [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
This is what my array looks like:
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
And I have the uuid key in the variable:
const uuid = '111-111-111';
Now based on this uuid, I would like to extract the value from the amountMoney: 44.04.
How do you write this in a nice way in js?
You can use Array.prototype.find:
items.find(item => item.uuid === uuid) // -> found object
Use Array.prototype.find to find the object if the property uuid of the object matches the value of the variable uuid. Before extracting the value for amountMoney check if the object was found.
Example,
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
const uuid = '111-111-111';
const foundItem = items.find(item => item.uuid === uuid);
if (foundItem) {
console.log(foundItem.amountMoney)
}

How to merge object inside object [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 4 years ago.
I have an array
var input = [["group1","group2","group3" ], ["group1", "group5" ]]
I would like to merge two objects like this :
["group1","group2","group3", "group1", "group5" ]
I tried to merge two objects in one array, however, I couldn't get the answer.
Any help would be appreciated.
I'm not too familiar with js, but can't you concat two arrays with something like
var merged = input[0].concat(input[1]);
You can use concat() like so:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = [].concat.apply([], input);
console.log(output);
Or alternatively, Array.prototype.flat():
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input.flat(1);
console.log(output);
Or if that is "hard" data, and will not change, you could use an even simpler concat() operation:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input[0].concat(input[1]);
console.log(output);
You can use the concat function to combine the arrays.
const resultArr = [];
input.forEach(curr => {
resultArr.concat(curr);
});
You're talking about 'flattening the array'...
const flatten = (array) => {
return array.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten([[1,2,[3]],4]));
ES5
array.reduce(function(a, x) { return a.concat(x); }, []);
ES6
array.reduce((a, x) => a.concat(x), []);
There is multiple approaches that you could take, my favorite would be to use the reduce method to transform your bi-dimensional array into one flat array and it would look like this :
function reducer(final_flat_array, inputItem) {
return [...final_flat_array, ...inputItem]
};
let flat_array = input.reduce(reducer, []);
or a more 'imperative' way I guess :
let flat_array = [];
input.forEach(item => flat_array.push(item);

Categories

Resources