如何用新的 属性 压平对象下划线?
How to Flatten Object Underscore with a new Property?
我有一个这样的数组:
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
]
如何使用下划线来展平数组中的年龄对象。预期结果是:
arr == [
{
name: 'John',
age: 'less than 19'
},
{
name: 'Doe',
age: 'more than 19'
}
];
谢谢,
你可以试试这个:
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
演示:
var arr = [{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
}, {
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}];
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
console.log(result);
希望对您有所帮助。
使用旧样式 :D
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
];
var newArr = [];
arr.forEach(function(item, idx) {
newArr.push({
name: item.name,
age: item.age.value
});
});
console.log(newArr);
我有一个这样的数组:
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
]
如何使用下划线来展平数组中的年龄对象。预期结果是:
arr == [
{
name: 'John',
age: 'less than 19'
},
{
name: 'Doe',
age: 'more than 19'
}
];
谢谢,
你可以试试这个:
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
演示:
var arr = [{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
}, {
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}];
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
console.log(result);
希望对您有所帮助。
使用旧样式 :D
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
];
var newArr = [];
arr.forEach(function(item, idx) {
newArr.push({
name: item.name,
age: item.age.value
});
});
console.log(newArr);