这是我的json:
[
{
"name": "1QQQJohnQQQ11_22_1998",
"age" : "ads"
},
{
"name": "2QQQEvaQQQ05_01_1989",
"age" : "ads"
},
{
"name": "3QQQCasperQQQ02_16_1994",
"age" : "ads"
},
{
"name": "4QQQBeanQQQ30_12_1996",
"age" : "ads"
}]
我从那张桌子做起,我要做的就是拆分" QQQ"来自名称并在3个字符串上进行更改(例如" 4"," Bean"," 30_12_1996"), 如何在js文件中,将每个字符串归为变量(例如,type =" 4",name =" Bean",date =" 30_12_1996)。 我的js文件:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get("filejson.json").then(function(data){
deferred.resolve(data);
});
this.getNames = function(){
return deferred.promise;
}
});
app.controller('MainCtrl', function($scope, service){
var promise = service.getNames();
promise.then(function(data){
$scope.names = data.data;
console.log($scope.names);
});
//*what i try to do (it didn't works):
var type = names.name.split('QQQ')[0];
var name= names.name.split('QQQ')[1];
var date= names.name.split('QQQ')[2];
//*
});
答案 0 :(得分:1)
您可以使用javascript map
函数将数组从一种格式映射到另一种格式,并使用字符串split
方法。
var a = [
{
name: "1QQQJohnQQQ11_22_1998",
age : "ads"
},
{
name: "2QQQEvaQQQ05_01_1989",
age : "ads"
},
{
name: "3QQQCasperQQQ02_16_1994",
age : "ads"
},
{
name: "4QQQBeanQQQ30_12_1996",
age : "ads"
}];
var result = a.map(function (value, index, array) {
varsplitValue = value.name.split("QQQ");
value["SNo"] = varsplitValue[0];
value["personName"] = varsplitValue[1];
value["dob"] = varsplitValue[2];
return value;
} );
调用map函数后, result
包含数组。
result[0].SNO
会显示第一个人的SNO(1)。
result[0].personName
会显示第一个人名(约翰)。
result[0].dob
会显示第一个出生日期(11_22_1998)。
答案 1 :(得分:0)
使用JavaScript **map() 方法:**
工作演示:
var a = [
{
name: "1QQQJohnQQQ11_22_1998",
age : "ads"
},
{
name: "2QQQEvaQQQ05_01_1989",
age : "ads"
},
{
name: "3QQQCasperQQQ02_16_1994",
age : "ads"
},
{
name: "4QQQBeanQQQ30_12_1996",
age : "ads"
}];
a.map(function(item) {
item.type = item.name.split('QQQ')[0];
item.date = item.name.split('QQQ')[2];
item.name = item.name.split('QQQ')[1];
});
console.log(a);