I have following object:
var obj = {"last_name": "john", "age": 23, "city": "London"}
I want to add a new element of first_name at the start of this object to look like this:
{"first_name": "Samuel", "last_name": "john", "age": 23, "city": "London"}
I know I can do obj.first_name = "Samuel" but it adds the new element at the end of the object. How can I add it at the start?
While objects have actually (ES5) no order, you could generate a new object with Object.assign and use the new property as object to start with and assign the given object to it. The new object has properties in creation order.
var object = { last_name: "john", age: 23, city: "London" };
object = Object.assign({ first_name: "Samuel" }, object);
console.log(object);
I tried, It works with spread operator. Do it in below way
var object = { last_name: "john", age: 23, city: "London" };
var newObject= { first_name: "Samuel" };
object = {...newObject, ...object }
o/p: { first_name: "Samuel", last_name: "john", age: 23, city: "London" };
Can do with spread operator, not confident about order
var object = { last_name: "john", age: 23, city: "London" };
var newObj={first_name: "Samuel" ,... object}
console.log(newObj);
Related
I need to generate csv for my client data but I need to include all headers came from my models.
The problem is some of my old client data has no existing fields. I want to create a new object with all the headers as a key and leave some empty string if a client has no data or no existing fields. Thanks for helping!
Here example of headers as key
let header = ["firstname", "lastname", "age", "gender", "address"];
Example for client info
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
Expected Output
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
address: "",
},
{
firstname: "Jane",
lastname: "Doe",
age: "",
gender: "",
address: "",
},
];
you can create an empty object with array.reduce
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
and use array.map on userInfo to return an object that concat the empty object with the one with value
let header = ["firstname", "lastname", "age", "gender", "address"];
let userInfo = [{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
const result = userInfo.map(user => {
return {
...emptyObj,
...user
};
})
console.log(result);
I have 2 arrays.
One array contains some people objects, the other array contains objects with name key that holds the value needed from the people objects.
My solution so far but not getting any luck....
When mapping over people array how do I return only certain properties from person? Not the entire person object
const customContactValues = people.map((person) => { return valuesNeeded.filter((el) => (el.name in person) ? person[el.name] : "" ) })
console.log(customContactValues)
Here is my people array
const people = [
{
"foods": {
"favoriteFood": "Ice cream"
},
"firstName": "John",
"lastName": "Doe",
"age": 30
},
{
"foods": {
"favoriteFood": "pizza"
},
"firstName": "Jane",
"lastName": "Doe",
"age": 39
},
{
"foods": {
"favoriteFood": "pbj"
},
"firstName": "Kevin",
"lastName": "Baker",
"age": 22
},
{
"foods": {
"favoriteFood": "pushpops"
},
"firstName": "ernie",
"lastName": "duncan",
"age": 29
},
]
Here is the values array which contains the keys I need from people array
const valuesNeeded = [
{ name: 'firstName' },
{ name: 'lastName' },
{ name: 'favoriteFood' }
]
I am trying to get and output like this below
const desiredResult = [
{firstName: "John", lastName: "Doe", favoriteFood: "Ice cream"},
{firstName: "Jane", lastName: "Doe", favoriteFood: "Pizza"},
{firstName: "Kevin", lastName: "Baker", favoriteFood: "pbj"},
{firstName: "ernie", lastName: "duncan", favoriteFood: "pushpops"}
]
filter only filters elements from array based on some condition but in your case we don't want to filter elements we just want to create new array of objects from and existing array so map function is a good start.
Second problem is the object can contain nested object which may contain required key value pair so to retrieve them we can recursively look over the value which is object if we don't find the key value directly in the object.
And since we don't want all the key value for each object in array we can either create a new object or delete from existing object, keeping the original is good and safe option if required for further processing.
const people = [{
"foods": {
"favoriteFood": "Ice cream"
},
"firstName": "John",
"lastName": "Doe",
"age": 30
},
{
"foods": {
"favoriteFood": "pizza"
},
"firstName": "Jane",
"lastName": "Doe",
"age": 39
},
{
"foods": {
"favoriteFood": "pbj"
},
"firstName": "Kevin",
"lastName": "Baker",
"age": 22
},
{
"foods": {
"favoriteFood": "pushpops"
},
"firstName": "ernie",
"lastName": "duncan",
"age": 29
},
];
// function to retrieve the key value recursively
function valueByKey(obj, key) {
let value = obj[key];
if (value) {
return value;
}
Object.keys(obj).forEach(function(k) {
if (typeof obj[k] == 'object') {
value = valueByKey(obj[k], key);
}
});
return value;
}
const valuesNeeded = [{
name: 'firstName'
},
{
name: 'lastName'
},
{
name: 'favoriteFood'
}
];
// creating new object by passing the current object and key
let output = people.map(function(item) {
let result = {};
valuesNeeded.forEach(function(obj) {
result[obj.name] = valueByKey(item, obj.name);
});
return result;
});
console.log(output);
You can search for the desired key on the top level, and go to child objects if not found. Here is my approach :
function getValue(obj, key) {
const keys = Object.keys(obj);
// Check if key exist on this level
if (keys.includes(key)) {
return obj[key];
} else {
// else we try to find in child objects
for (k of keys) {
if (typeof obj[k] == 'object') {
return getValue(obj[k], key);
}
}
}
//Return this if not found
return '';
}
const people = [
{
foods: {
favoriteFood: 'Ice cream',
},
firstName: 'John',
lastName: 'Doe',
age: 30,
},
{
foods: {
favoriteFood: 'pizza',
},
firstName: 'Jane',
lastName: 'Doe',
age: 39,
},
{
foods: {
favoriteFood: 'pbj',
},
firstName: 'Kevin',
lastName: 'Baker',
age: 22,
},
{
foods: {
favoriteFood: 'pushpops',
},
firstName: 'ernie',
lastName: 'duncan',
age: 29,
},
];
const valuesNeeded = [
{ name: 'firstName' },
{ name: 'lastName' },
{ name: 'favoriteFood' },
];
let output = people.map((item) => {
let result = {};
valuesNeeded.forEach(function (obj) {
result[obj.name] = getValue(item, obj.name);
});
return result;
});
console.log(output);
Edit 1 : You can further simplify valuesNeeded to keysNeeded and store only the keys in an array like this keysNeeded = ['firatName', 'lastName', 'favoriteFood']. Please change invocation accordingly.
I have parent object in which data appears as following:
name is first, gender is second and address is third
[{name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura"},
{name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura"}]
I want to push another object in the above array but incoming data is in juggled way, for example
{address: "makarpura GIDC, GIDC Makarpura", gender: "male", name: "alpesh solanki"}
In the sense, address is first, gender is second and name is third
But I want to arrange it according to parent object.
The sortes approach is to take an object with the wanted keys in order as template and map all object by assigning the properties to a new object with an empty object, the template and the actual object.
The result is an array with object's properties in wanted order.
var data = [{ name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura" }, { name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura" }],
template = { address: null, gender: null, name: null },
result = data.map(o => Object.assign({}, template, o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can't sort properties in an Object.
But if you want to sort properties in every objects of the array you can create a new newData array with the method Array.prototype.map() and Destructuring assignment with the desired properties order data.map(({address, gender, name}) => ({address, gender, name}))
Code:
const data = [{name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura"}, {name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura"}];
const newData = data.map(({address, gender, name}) => ({address, gender, name}));
console.log(newData);
I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...
Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.
I have an object:
person = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
}
I have an array of key names in given order:
keys = ["occupation", "last_name", "city"]
I want to get this array:
["Doctor", "Doe", "Boston"]
It is important, that the answer should guarantee the order (JavaScript does not guarantee the order for object iteration).
I think there is probably some utility function in lodash/underscore to do it simply, but can't figure out any.
You can use Array.prototype.map for this. Map loops through an array and creates a new array by applying a function to each item. When you use the keys array as a starting point, and return the value in o for that key, you'll get a new array with only values.
When using "dynamic" key names, you use a object[stringKeyName] notation to retrieve a value.
var o = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
};
var keys = ["occupation", "last_name", "city"];
var result = keys.map(function(k) { return o[k]; });
console.log(result);
If it fits your style, you can create a helper method to replace the anonymous function:
var o = { birth_year: 1970, first_name: "John", last_name: "Doe", occupation: "Doctor", city: "Boston", married: true };
var keys = ["occupation", "last_name", "city"];
var prop = obj => key => obj[key];
var result = keys.map(prop(o));
console.log(result);
With Lodash you could use pick and values
var o = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
}
var keys = ["occupation", "last_name", "city"];
var result = _.values(_.pick(o, keys));
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>