How can i separate key/value in different array object in js? - javascript

I have this in my code:
let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
let i;
for (i= obj;i<=obj;i++)
{
years.push({ edad_beneficiario : i })
}
the output is
[
edad_beneficiario:{EdadBeneficiario1:"32", EdadBeneficiario2:"5"}
]
but what i want is this
[
{edad_beneficiario:"32"},
{edad_beneficiario:"5"}
]
what can i do?
EDIT
By the way, if i do this
years.push({ edad_beneficiario :obj.EdadBeneficiario1})
years.push({ edad_beneficiario :obj.EdadBeneficiario2})
the output what i want resolve but i want it to do it with a for loop. Please, Help.

The problem is that in the loop, you are setting i = obj, then i = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}. i must be a integer value to work with the for loop in this case. You can use Object.values method to transform obj values into an array and get it's data to use it in the for loop.
let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
let objValuesArray = Object.values(obj);
for (let i = 0; i < objValuesArray.length; i++) {
years.push({ edad_beneficiario : objValuesArray[i] })
}

Does this work for you? Use Object.values() and Array.map() to get the desired output.
let obj = {
EdadBeneficiario1: '32',
EdadBeneficiario2: '5'
}
const output = Object.values(obj).map(value => ({
edad_beneficiario: value
}));
console.log(output);

let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
Object.entries(obj).map(([key, value]) => {
years.push( {edad_beneficiario: value} )
}
)
console.log(years)
/*
Array [ {…}, {…} ]
​ 0: Object { edad_beneficiario: "32" }
​ 1: Object { edad_beneficiario: "5" }
*/

const myFunc = (obj) => {
const years = Object.keys(obj).map((c, i) => {
const values = Object.values(obj).map((b) => b);
return { edad_beneficiario: values[i] };
});
console.log(years);
};
you can actually make it a lot shorter but i just wanted you to know that you can access object keys as well .

Related

How to update an object value in array of objects when the keys are same

I have an Array of objects and one object
const filterArray = [{bestTimeToVisit: 'Before 10am'}, {bestDayToVisit: Monday}]
This values are setting in a reducer and the payload will be like
{bestTimeToVisit: 'After 10am'}
or
{bestDayToVisit: Tuesday}.
So what I need is when I get a payload {bestTimeToVisit: 'After 10am'} and if bestTimeToVisit not in filterList array, then add this value to the filterList array.
And if bestTimeToVisit already in the array with different value, then replace the value of that object with same key
if(filterArray.hasOwnProperty("bestTimeToVisit")) {
filterArray["bestTimeToVisit"] = payload["bestTimeToVisit"];
} else {
filterArray.push({"bestTimeToVisit": payload["bestTimeToVisit"]});
}
I convert the object array into a regular object and then back into an object array. makes things less complicated. I'm making the assumption each object coming back only has one key/value and that order doesnt matter.
const objectArraytoObject = (arr) =>
arr.reduce((acc, item) => {
const key = [Object.keys(item)[0]];
return { ...acc, [key]: item[key] };
}, {});
const newValues = [{ someKey: 'something' }, { bestDayToVisit: 'Tuesday' }];
const filterArray = [
{ bestTimeToVisit: 'Before 10am' },
{ bestDayToVisit: 'Monday' },
];
const newValuesObj = objectArraytoObject(newValues);
const filterObj = objectArraytoObject(filterArray);
const combined = { ...filterObj, ...newValuesObj };
const combinedToArray = Object.keys(combined).map((key) => ({
[key]: combined[key],
}));
console.log(combinedToArray);
Need to iterate over the array and find objects that satisfy for modification or addition if none are found.
function checkReduced(filterrray,valueToCheck="After 10am"){
let isNotFound =true;
for(let timeItem of filterrray) {
if(timeItem.bestTimeToVisit && timeItem.bestTimeToVisit !== valueToCheck) {
timeItem.bestTimeToVisit=valueToCheck;
isNotFound=false;
break;
}
}
if(isNotFound){filterrray.push({bestTimeToVisit:valueToCheck})}
}
const filterArray = [{bestDayToVisit: "Monday"}];
checkReduced(filterArray,"After 9am");//calling the function
const updateOrAdd = (arr, newItem) => {
// get the new item key
const newItemKey = Object.keys(newItem)[0];
// get the object have the same key
const find = arr.find(item => Object.keys(item).includes(newItemKey));
if(find) { // the find object is a reference type
find[newItemKey] = newItem[newItemKey]; // update the value
} else {
arr.push(newItem); // push new item if there is no object have the same key
}
return arr;
}
// tests
updateOrAdd([{ a: 1 }], { b: 2 }) // => [{ a: 1 }, { b: 2 }]
updateOrAdd([{ a: 1 }], { a: 2 }) // => [{ a: 2 }]

How to determine if object is array-like and convert it into array?

I'm using dep-object-diff, which returns differences between two objects.
The problem is that if I have something like,
const objectA = {
fieldA: 5,
fieldB: ['123']
}
const objectB = {
fieldA: 5,
fieldB: ['123', '456']
}
Then it returns,
const diff = {
fieldB: {
0: '456'
}
}
When the required response object should be,
const diff = {
fieldB: ['456']
}
How can I detect if diff.fieldB is an array (dynamically, without hardcoding), and consequently convert it into one?
Edit
Thanks to #Nina Scholz, I ended up using her approach as the base. The problem which I caught with my data, however, was that the approach didn't work for strings. Anyway, I ended up implementing it as follows:
const diffs = {
fieldA: "SOME_STRING",
fieldB: {
3: '123',
5: '456'
},
};
const chronologize = (object) => {
let counter = 0;
for (let prop in object) {
if (object[prop]) {
object[counter] = object[prop];
delete object[prop];
counter++;
}
}
return object;
};
const result = Object.fromEntries(
Object.entries(diffs).map(([k, v]) =>
typeof v === 'string'
? [k, v]
: [k, Object.assign([], chronologize(v))]),
);
console.log(result);
You could get the entries, convert the array like object to array with Object.assign and an array as target and convert back to an object.
const
diff = { fieldB: { 0: '456' } },
result = Object.fromEntries(Object.entries(diff).map(([k, v]) => [k, Object.assign([], v)]));
console.log(result);

how to convert nested array of objects to object of array

I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);

Merge two dimensional array into array of objects

I would like to know how would I merge this bidimensional array
let arr[
['Reference', 'Price'],
['232323DD, 15.00]
];
I want to convert this into
[
{name: 'Reference', value: '232323DD'},
{name: 'Price', value: 15.00}
]
I've tried this:
Convert a two dimensional array into an array of objects
but It didn't work for me.
You can use .map():
let [keys, values] = [
['Reference', 'Price'],
['232323DD', 15.00]
];
let result = keys.map((k, i) => ({name: k, value: values[i]}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map through the first array in that array and use their values as the keys to an object:
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
console.log(
arr[0].map((name, i) => ({name, value:arr[1][i]}))
)
If you are unsure about the size of the two arrays, you should first check whether their lengths are equal, to avoid undefined.
Other solution if you are not familiar with map (I think using map for this example make it a bit hard to read)...
const arr = [
['Reference', 'Price'],
['232323DD', 15.00]
]
const obj = []
arr.forEach(x => obj.push({name: x[0], value: x[1]}))
console.log(obj)
You can use the map function. It will run the callback on each array item, return it in a new array.
// where 'arr' is your original array
const new_arr = arr.map((item) => {
// this is called a 'destructuring assignment'
const [name, value] = item;
// return the values as fields in an object
return {name, value};
});
const arrArr = [['Reference', 'Price'], ['232323DD, 15.00]];
const objArr = [];
for (const item of arrArr) {
objArr.push({name: item[0], value: item[1]});
}
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
let result = arr[0].map((key, i) => ({name: key, value: arr[1] ? arr[1][i] : null}));
console.log(result);
I'll try to break this down:
// 1. create a new arr object:
let convertedArr = [];
// 2. loop over the original array:
for(let i = 0; i < arr.length; i++){
let currentItem = arr[i];
//create a temp object
let obj = {name:currentItem[0], value: name:currentItem[1] };
//push a new object to the array
convertedArr.push(obj);
}

How to turn this array into a JavaScript object?

The following code loops through a JavaScript object and collects only the properties that are arrays:
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
In other words, it takes this:
{
name: '',
description: ''.
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
and turns it into this:
[
{ livingroom: Array[0] },
{ study: Array[1] },
{ bedroom: Array[0] }
]
However, what I need to produce is this:
{
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
How to accomplish that?
Change this :
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
to this :
const building = this.building
let panoramaList = {}
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key]=panoramas
}
}
console.log(panoramaList)
Use Object.keys and try something like this:
var input = {} //...your input array
var keys = Object.keys(input);
var result = {};
keys.forEach(function (key) {
if (Array.isArray(input[key])) {
result[key] = input[key];
}
});
try this
var output = Object.keys(building).map(function(val){ return { val : building[val] } });
For the final output
var panoramaList = {}
Object.keys(building).forEach(function(val){
if ( Array.isArray(building[val] )
{
panoramaList[val] = building[val];
}
});
Make sure to define panoramaList as an object.
This works
var arrays = {
name: '',
description: '',
livingroom: ['1','www'],
study: ['2','sss'],
bedroom: ['3','aaa'],
Kitchen: ['4','bbb'],
}
const building = arrays
let panoramaList = {};
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key] = panoramas;
}
}
console.log(panoramaList);
https://jsbin.com/paqebupiva/1/edit?js,console,output
Rather than building a new object, you might just need to delete the unwanted properties from the object that you have:
var data = {
name: '',
description: '',
livingroom: [],
study: [1],
bedroom: [0]
};
Object.keys(data).forEach(function(key) {
if (!Array.isArray(data[key])) delete data[key];
})
document.write(JSON.stringify(data));

Categories