How extract Object with "{ }" from an string [duplicate] - javascript

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Closed 3 years ago.
I try to extract Object from bellow array :
var array = [];
array =
a,b,c,{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},c,b
imagine extract this :
result = [
{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"}
]
I use my code but didn't give me the right answer :
for (var i =0 ; i < array.length ; i++) {
console.log((array[i].split(','));
}
In this code I just get each variable in each line
I need more thing because in each time maybe I have different
array that has for example 2 Object in this example I just have
3 Object.I try to define If I has any Object I can find them and push them in one array.

You can use Array.filter
var array = [];
array = [
'a','b','c',{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},'c','b'
];
let result = array.filter(e => typeof e === 'object');
console.log(result)

You can use array reduce function. Inside reduce callback check if the type of the element is object then in accumulator array push the element
var array = [];
array = [
'a', 'b', 'c', {
"A": "0",
"f": "1",
"g": "2"
}, {
"B": "5",
"v": "8",
"x": "4"
}, {
"C": "0",
"f": "1",
"g": "2"
},
'c', 'b'
];
let newArr = array.reduce((acc, curr) => {
if (typeof(curr) === 'object') {
acc.push(curr)
}
return acc;
}, []);
console.log(newArr)

Related

Insert all properties from an object within an array to another object in array using JS/TS

I have been looking a simple way to copy/insert/move properties in an object within an array to another object. I came up with a basic logic which does the job perfectly but am not satisfied with this. There has to be a better way, any help here?
var first = [
{
"AGREE_EFF_DATE__0": "02-Aug-2018",
"AGREE_TERM_DATE__0": "30-Apr-2021",
"AGREE_IND__0": "P1",
"P_DBAR_IND__0": "N",
"AGREE_EFF_DATE__1": "01-May-2021",
"AGREE_TERM_DATE__1": null,
"AGREE_IND__1": "NP",
"P_DBAR_IND__1": "N",
"PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
"PROVIDER_SPECIALITY_CODE__0": "CK"
}
];
var second = [
{
"STATUS": "ACTIVE",
"MEDICARE_NUMBER" : 12345
}
];
for(let i = 0; i < second.length; i++) {
var first_keys = Object.keys(first[i]);
var first_values = Object.values(first[i]);
for(let j = 0; j < first_keys.length; j++) {
second[i][first_keys[j]] = first_values[j];
}
}
console.log(second);
//Output-
[
{
STATUS: 'ACTIVE',
MEDICARE_NUMBER: 12345,
AGREE_EFF_DATE__0: '02-Aug-2018',
AGREE_TERM_DATE__0: '30-Apr-2021',
AGREE_IND__0: 'P1',
P_DBAR_IND__0: 'N',
AGREE_EFF_DATE__1: '01-May-2021',
AGREE_TERM_DATE__1: null,
AGREE_IND__1: 'NP',
P_DBAR_IND__1: 'N',
PROVIDER_SPECIALITY__0: 'PSYCHOLOGY, CLINICAL',
PROVIDER_SPECIALITY_CODE__0: 'CK'
}
]
When possible, you should prefer iteration to manually indexed loops. This means arr.map() or arr.forEach() or arr.reduce(), to name a few.
Also, You can use an object spread to easily merge objects together.
Putting those together, you can reduce this logic to:
const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))
Here we map() over all members of first, which returns a new array where each member is the result of the function. This function takes the array member as the first argument, and the index of that member as the second argument. Then we can use that index to find the corresponding item in the second array.
Then you just spread both objects into a new object to assemble the final result.
var first = [
{ a: 1, b: 2 },
{ a: 4, b: 5 },
];
var second = [
{ c: 3 },
{ c: 6 },
];
const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))
console.log(result)
Which is all perfectly valid typescript as well.
NOTE: there is one difference between my code any yours. Your code modifies the objects in second. My code returns new objects and does not change the contents of second at all.
This is usually the better choice, but it depends on how you use this value and how data is expected to flow around your program.
You need to be careful with iterating, because you can have different count of elements in first and second arrays. So the possible solution will be like this:
const first = [
{
"AGREE_EFF_DATE__0": "02-Aug-2018",
"AGREE_TERM_DATE__0": "30-Apr-2021",
"AGREE_IND__0": "P1",
"P_DBAR_IND__0": "N",
"AGREE_EFF_DATE__1": "01-May-2021",
"AGREE_TERM_DATE__1": null,
"AGREE_IND__1": "NP",
"P_DBAR_IND__1": "N",
"PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
"PROVIDER_SPECIALITY_CODE__0": "CK"
}
];
const second = [
{
"STATUS": "ACTIVE",
"MEDICARE_NUMBER": 12345
}
];
console.log(mergeAll(first, second));
function mergeAll(firstArray, secondArray) {
const result = [];
const minLength = firstArray.length < secondArray.length ? firstArray.length : secondArray.length;
for (let i = 0; i < minLength; i++) {
result.push({...firstArray[i], ...secondArray[i]});
}
return result;
}

foreach array with one key [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 1 year ago.
I've got an object with different values .
let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]
How can I foreach them and then put them in an object and pick a name for them like this :
"photo_type": {
"Personal": "1000",
"sport": "2100",
"Industrial": "1200",
"Commercial": "2300",
"Fashion": "1300",
"Documentary": "2600"
}
I dont want them to be like 0 and 1 and 2.
You could create an object with Object.assign and by spreading the array.
let array = [{ Personal: "1000" }, { sport: "2100" }, { Industrial: "1200" }, { Commercial: "2300" }, { Fashion: "1300" }, { Documentary: "2600" }],
object = Object.assign({}, ...array);
console.log(object);
You can try this
const arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},{"Fashion": "1300"},{"Documentary": "2600"}]
let result = {}
arr.forEach(member => {result = {...result, ...member}}

How to merge objects by value and change property type?

I have this array of objects
[ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ]
I want to:
Merge objects by value attribute
Change hobbies property to an array
Merge property values
The expected output
[ { "value": "1", "hobbies": ['netflix','food']}]
Using reduce comes in handy here as it helps you iterate over the array and keep an accumulator to store the data in each iteration.
I set the acc to be a JSON object (key-value pairs) where the key is the value attribute and the value is the resulting item with this value.
Along the way, if there is no item with the given key in the acc, we add the object as it is while setting hobbies as an array instead of a string.
Otherwise, if it does contain such an object, we add it's value to the existinghobbies list.
Finally, we take the values of the resulting object which gives the list of grouped objects.:
const arr = [
{ "value": "1", "hobbies": 'netflix'},
{ "value": "2", "hobbies": 'reading'},
{ "value": "1", "hobbies": 'food'},
];
const res = Object.values(
arr.reduce((acc,item) => {
const { value, hobbies } = item;
acc[value] = acc[value]
? { ...acc[value], hobbies: [...acc[value].hobbies, item.hobbies] }
: { ...item, hobbies: [hobbies] };
console.log(acc);
return acc;
}, {})
);
console.log(res);
You can use a forEach loop to iterate through the array.
var arr = [ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ];
var k = {};
var out = [];
arr.forEach(elm => {
if(typeof(k[elm.value]) == "undefined")
k[elm.value] = {value:elm.value, hobbies:[]};
k[elm.value].hobbies.push(elm.hobbies);
});
Object.keys(k).forEach(key => out.push(k[key]));
console.log(out);
You can use Array#reduce with an object to store the result for each value. On each iteration, if the current value does not exist as a key in the accumulator object, we create it and initialize the hobbies property as an empty array. Then, we add the current hobby to the object at that value. After the reduce operation, we use Object.values to get an array of all the resulting values.
const arr = [ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ];
const res = Object.values(
arr.reduce((acc,{value, hobbies})=>
((acc[value] = acc[value] || {value, hobbies: []}).hobbies.push(hobbies), acc),
{}));
console.log(res);

Getting key of each object inside array of objects into an array: Javascript

I have an object with the following format
var obj = [{
"a": 1
}, {
"b": 2
}, {
"c": 3
}];
Would want to fetch only keys out of each object inside this array of objects into a new array
Something like this:
["a","b","c"]
Have tried the following but it is not working :
var obj = [{
"a": 1
}, {
"b": 2
}, {
"c": 3
}];
let result = obj.map (({ val }) => val)
console.log(result);
Merge to a single object by spreading into Object.assign(), and then get the keys:
var obj = [{"a":1},{"b":2},{"c":3}];
const result = Object.keys(Object.assign({}, ...obj));
console.log(result);
Or use Array.flatMap() with Object.keys():
var obj = [{"a":1},{"b":2},{"c":3}];
const result = obj.flatMap(Object.keys);
console.log(result);
I'd .map and extract the first item in the Object.keys of the object being iterated over:
var obj = [{
"a": 1
}, {
"b": 2
}, {
"c": 3
}];
const result = obj.map(inner => Object.keys(inner)[0]);
console.log(result);
You can make use of Object.assign and spread(...) operator to solve this issue
var mainObj = [{"a":1},{"b":2},{"c":3},{"23":1},{"32b":2},{"232c":3}];
const allKeys = Object.keys(Object.assign({}, ...mainObj));
console.log(allKeys);
You can simply use .map() to open the array and then use Object.keys to return the key from the object.
Please refer the example I have made.I hope it helps
https://www.w3schools.com/code/tryit.asp?filename=G66AEBM9ZJCD
let object1 = [{a:1,b:2,c:3}]
let final = object1.map(function(object){
return Object.keys(object)
});

Selecting data from an array as an Object

var myObj = [
{"a":"1", "b":"2"},
{"c":"3", "c":"4"},
{"d":"5", "e":"6"}
];
What is the best solution to pick one of the rows? I have this function below which convert the Object to array, but it returns indexes, though I need the full row.
var array = $.map(myObj, function(value, index) {
return value;
});
return array;
}
var myObj = [{
"a": "1",
"b": "2"
}, {
"c": "3",
"c": "4"
}, {
"d": "5",
"e": "6"
}];
var reformattedArray = myObj.map(function(value, index, array) {
return Object.values(value);
});
console.log(reformattedArray);
If the desired output is, for example:
[
"a",
"b"
]
Do:
var myObj = [
{"a":"1", "b":"2"},
{"c":"3", "c":"4"},
{"d":"5", "e":"6"}
];
var newArr = myObj.map(row => Object.keys(row));
console.log(newArr[0]);

Categories

Resources